亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

Chinaunix

標(biāo)題: lua寫成的排列組合算法,為什么排列的結(jié)果正確,組合的結(jié)果不正確? [打印本頁]

作者: ssfjhh    時(shí)間: 2013-12-15 21:49
標(biāo)題: lua寫成的排列組合算法,為什么排列的結(jié)果正確,組合的結(jié)果不正確?
本帖最后由 ssfjhh 于 2013-12-17 11:37 編輯
  1. function echo (items)
  2.     for i = 1, #items do
  3.         io.write(items[i], ' ')
  4.     end
  5.     io.write('\n')
  6. end

  7. local function arrangement (items, n)
  8.     n = n or #items
  9.     if n == 0 then
  10.         coroutine.yield({})
  11.     else
  12.         for i = 1, #items do
  13.             local h = table.remove(items, 1)
  14.             for e in arrange(items, n-1) do
  15.                 table.insert(e, 1, h)
  16.                 coroutine.yield(e)
  17.             end
  18.             table.insert(items, h)
  19.         end
  20.     end
  21. end

  22. function arrange (items, n)
  23.     local co = coroutine.create(function () arrangement(items, n) end)
  24.     return function ()
  25.         local code, res = coroutine.resume(co)
  26.         return res
  27.     end
  28. end

  29. local function combination (items, n)
  30.     n = n or #items
  31.     if n == 0 then
  32.         coroutine.yield({})
  33.     else
  34.         for i = 1, #items do
  35.             local h = table.remove(items, 1)
  36.             for e in combinate(items, n-1) do
  37.                 table.insert(e, 1, h)
  38.                 coroutine.yield(e)
  39.             end
  40.         end
  41.     end
  42. end

  43. function combinate (items, n)
  44.     local co = coroutine.create(function () combination(items, n) end)
  45.     return function ()
  46.         local code, res = coroutine.resume(co)
  47.         return res
  48.     end
  49. end

  50. for e in arrange({'a', 'b', 'c'}) do
  51.     echo(e)
  52. end

  53. print('\n~~~~~~~~~~~~~~~~~~~~~~')
  54.             
  55. for e in combinate({'a', 'b', 'c', 'd'}, 3) do
  56.     echo(e)
  57. end
復(fù)制代碼
理解不能呀,排列的結(jié)果正確,組合的結(jié)果不正確,實(shí)在檢查不出原因,我只好先用python寫成,發(fā)現(xiàn)算法沒有問題,排列和組合的結(jié)果都正確,但是從python翻譯過來的組合算法死活都不對(duì),為什么呢?  而且排列只不過比組合算法多了一行代碼而已,為什么排列的結(jié)果正確?






歡迎光臨 Chinaunix (http://72891.cn/) Powered by Discuz! X3.2