- 论坛徽章:
- 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
复制代码 理解不能呀,排列的结果正确,组合的结果不正确,实在检查不出原因,我只好先用python写成,发现算法没有问题,排列和组合的结果都正确,但是从python翻译过来的组合算法死活都不对,为什么呢? 而且排列只不过比组合算法多了一行代码而已,为什么排列的结果正确?
|
|