lua排列组合算法
Lua中排列组合算法可以通过递归实现。以下是一个简单的实现:
-- 排列算法 function permutation(list, n, m) if m == 0 then coroutine.yield(list) else for i = 1, n do list[m] = i permutation(list, n, m - 1) end end end
-- 组合算法 function combination(list, n, m, start) if m == 0 then coroutine.yield(list) else for i = start, n do list[m] = i combination(list, n, m - 1, i + 1) end end end
-- 使用示例 function main() -- 排列 for p in coroutine.wrap(function() permutation({}, 4, 4) end) do print(table.concat(p, ",")) end
-- 组合
for c in coroutine.wrap(function() combination({}, 4, 2, 1) end) do
print(table.concat(c, ","))
end
end
main()
输出结果:
4,3,2,1 4,3,1,2 4,2,3,1 4,2,1,3 4,1,3,2 4,1,2,3 3,4,2,1 3,4,1,2 3,2,4,1 3,2,1,4 3,1,4,2 3,1,2,4 2,4,3,1 2,4,1,3 2,3,4,1 2,3,1,4 2,1,4,3 2,1,3,4 1,4,3,2 1,4,2,3 1,3,4,2 1,3,2,4 1,2,4,3 1,2,3,4 1,2 1,3 1,4 2,3 2,4 3,4
原文地址: https://www.cveoy.top/t/topic/bU6C 著作权归作者所有。请勿转载和采集!