免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2258 | 回复: 0
打印 上一主题 下一主题

[算法] lua写成的排列组合算法,为什么排列的结果正确,组合的结果不正确? [复制链接]

论坛徽章:
4
金牛座
日期:2013-10-11 16:12:50卯兔
日期:2014-07-31 09:17:19辰龙
日期:2014-08-08 09:28:02狮子座
日期:2014-09-14 20:32:05
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-12-15 21:49 |只看该作者 |倒序浏览
本帖最后由 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
复制代码
理解不能呀,排列的结果正确,组合的结果不正确,实在检查不出原因,我只好先用python写成,发现算法没有问题,排列和组合的结果都正确,但是从python翻译过来的组合算法死活都不对,为什么呢?  而且排列只不过比组合算法多了一行代码而已,为什么排列的结果正确?

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP