6.1 略
6.2 用lselect(2,…)函式
6.3
6.4function f63(.
..) local t = table.
pack(.
..) t[t.n]
= nil
t.n = t.n-
1return table.
unpack
(t)end
(f63(2
,3,4
,5))
說下思路
pair每乙個元素,把每個元素都隨機從陣列中選擇乙個索引的元素進行交換。
6.5function f64
(t)for i =
1,#t do
index = math.
random(1
,#t)
a = t[i]
t[i]
= t[index]
t[index]
= a end
return table.
unpack
(t)end
(f64()
)
求全組合
6.6res =
tmp =
function f65
(arr,x)
f652
(arr,1,
1,x)
end--arr-陣列 n-選擇組合中第幾個方法 i-從第幾個索引開始取 x-需要取多少個元素
function f652
(arr,n,i,x)
if(n>x) then
res[#res+1]
=return
endfor k = i, #arr do
tmp[n]
= arr[k]
f652
(arr,n+
1,k+
1,x)
endendf65(,
3)for i =
1, #res do
for z =
1, #res[i]
do io.
write
(res[i]
[z])
endio.
write
("\n"
)end
動態語言的函式呼叫,即使沒有遞迴所占用的棧空間也是不確定的,因為lua函式的引數值和返回值和他們的型別不確定
f()g()
g()f()
《Lua程式設計 第4版 》 第7章練習答案
function exercise7 1and2 filename1,filename2 local inputf,outputf if filename1 and filename2 then inputf io.open filename1,r local filetest io.open fi...
《Lua程式設計 第4版 》 第9章練習答案
lua的閉包真的很強大!function derivative f,delta delta delta or 1e 5 return function x return f x delta f x delta endendfunction integral f,delta delta delta o...
《Lua程式設計 第4版 》 第5章練習答案
monday sunday sunday 一樣,都指向該錶。a.a.a.a 3,執行的是該錶的索引 a 賦值為3,之後的a.a.a.a將會引發異常,因現a.a 3,而非表。在方括號裡寫索引值 tab for i,j in pairs tab do io.write i,j,n endfunction...