1. 程式人生 > >《Lua程式設計(第4版)》:第5章練習答案

《Lua程式設計(第4版)》:第5章練習答案

練習5.1

monday sunday sunday

練習5.2

一樣,都指向該表。

a.a.a.a=3,執行的是該表的索引 a 賦值為3,之後的a.a.a.a將會引發異常,因現a.a=3,而非表。

練習5.3

在方括號裡寫索引值

tab={["\n"]=1,["\n\t\a"]=666,["lisper"]="lua"}
for i,j in pairs(tab) do
  io.write(">",i,">>",j,"\n")
end

練習5.4

function ans_s(t,x)
  local sp=t[1]
  for i=2,#t do
    sp=sp+t[i]*x^(i-1)
  end
  return sp
end

練習5.5

function ans(t,x)
  local sp=t[1]
  local dp=x
  for i=2,#t do
    sp=sp+dp*t[i]
    dp=dp*x
  end
  return sp
end

練習5.6

對比ipairs和pairs迭代器迴圈次數

function ispair(t)
  local x,y
  for i in pairs(t) do
    x=i
  end
  for i in ipairs(t) do
    y=i
  end
  if x~=y then
    return false
  else
    return true
  end
end

練習5.7

function movetable(t1,t2,n)
  table.move(t1,1,#t1,n,t2)
  return t2
end

練習5.8

簡單二分優化實現表字符串元素連線函式

function tabconcat(tab)
  local len,con=0,0
  len=#tab
  repeat
    if len%2==1 then
      len=len-1
      con=1
    else
      con=0
    end
    for i=1,len/2,1 do
      tab[i]=tab[2*i-1]..tab[2*i]
    end
    if con==1 then
      tab[len/2+1]=tab[len+1]
      len=len/2+1
    else
      len=len/2
    end
  until len==1
  return tab[1]
end

與標準庫table.concat函式進行對比測試。

function test(tm)
  print(">> ",tm," * a concat")
  tab1={}
  for i=1,tm do
    tab1[i]="a"
  end
  time=os.time()
  str1=tabconcat(tab1)
  print(os.time()-time,#str1)

  tab2={}
  for i=1,tm do
    tab2[i]="a"
  end
  time=os.time()
  str2=table.concat(tab2)
  print(os.time()-time,#str2)
end

--test(1000000)
--test(10000000)
--test(100000000)

測試結果:

>>      1000000  * a concat
1       1000000
1       1000000
>>      10000000  * a concat
9       10000000
4       10000000
>>      100000000  * a concat
93      100000000
44      100000000

一百萬個“a”相連,相差約0s

一千萬個“a“相連,相差5s

一億個”a"相連,相差49s

END