《Lua程序设计(第4版)》:第6章练习答案

练习6-1

function exercise6_1(array)
  for i=1,#array,1 do
    io.write(table.unpack(array,i,i)," ")
  end
end

练习6-2

function exercise6_2(num,...)
  local sp=table.pack(...)
  for i=1,#sp,1 do
    io.write(sp[i]," ")
  end
end

练习6-3

function exercise6_3(...)
  local sp=table.pack(...)
  for i=1,#sp-1,1 do
    io.write(sp[i]," ")
  end
end

练习6-4

经典洗牌算法

function exercise6_4(tab)
  math.randomseed(os.time())
  for i=#tab,2,-1 do
    local randnum=math.random(i)
    local sp=tab[i]
    tab[i]=tab[randnum]
    tab[randnum]=sp
  end
  return tab
end

练习6-5

function exercise6_5(tab,begin)
  begin=begin or 0
  if begin==0 then
    exercise6_5_name=1
  end
  if exercise6_5_anstable==nil or begin==0 then
    exercise6_5_anstable={}
  end
  if exercise6_5_sptable==nil or begin==0 then
    exercise6_5_sptable={}
  end
  if begin==(#tab) then
    exercise6_5_anstable[exercise6_5_name]=table.move(exercise6_5_sptable,1,#exercise6_5_sptable,1,{})
    exercise6_5_name=exercise6_5_name+1
  else
    table.insert(exercise6_5_sptable,tab[begin+1])
    exercise6_5(tab,begin+1)
    table.remove(exercise6_5_sptable)
    exercise6_5(tab,begin+1)
  end
  return exercise6_5_anstable
end

返回一个序列,其中包含着若干个序列,是输入序列元素的所有可能组合。

注意每次递归出现结果时,给序列赋值的应该是存储临时结果的表的克隆!

调用方法如下

array={1,2,3,4,5}
ans=exercise6_5(array)
for i=1,#ans do
  print(table.unpack(ans[i]))
end
print(#ans)

练习6-6

这题不太懂,个人感觉是动态语言的函数调用时,即使没有使用递归所占用的栈空间也不是确定的。

因为Lua函数的参数值、返回值和他们的类型都是不确定的。

先留个坑,以后补。

end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值