- 論壇徽章:
- 4
|
本帖最后由 ssfjhh 于 2013-12-17 11:37 編輯
- function echo (items)
- for i = 1, #items do
- io.write(items[i], ' ')
- end
- io.write('\n')
- end
- local function arrangement (items, n)
- n = n or #items
- if n == 0 then
- coroutine.yield({})
- else
- for i = 1, #items do
- local h = table.remove(items, 1)
- for e in arrange(items, n-1) do
- table.insert(e, 1, h)
- coroutine.yield(e)
- end
- table.insert(items, h)
- end
- end
- end
- function arrange (items, n)
- local co = coroutine.create(function () arrangement(items, n) end)
- return function ()
- local code, res = coroutine.resume(co)
- return res
- end
- end
- local function combination (items, n)
- n = n or #items
- if n == 0 then
- coroutine.yield({})
- else
- for i = 1, #items do
- local h = table.remove(items, 1)
- for e in combinate(items, n-1) do
- table.insert(e, 1, h)
- coroutine.yield(e)
- end
- end
- end
- end
- function combinate (items, n)
- local co = coroutine.create(function () combination(items, n) end)
- return function ()
- local code, res = coroutine.resume(co)
- return res
- end
- end
- for e in arrange({'a', 'b', 'c'}) do
- echo(e)
- end
- print('\n~~~~~~~~~~~~~~~~~~~~~~')
-
- for e in combinate({'a', 'b', 'c', 'd'}, 3) do
- echo(e)
- end
復(fù)制代碼 理解不能呀,排列的結(jié)果正確,組合的結(jié)果不正確,實(shí)在檢查不出原因,我只好先用python寫(xiě)成,發(fā)現(xiàn)算法沒(méi)有問(wèn)題,排列和組合的結(jié)果都正確,但是從python翻譯過(guò)來(lái)的組合算法死活都不對(duì),為什么呢? 而且排列只不過(guò)比組合算法多了一行代碼而已,為什么排列的結(jié)果正確?
|
|