Skip to content

Instantly share code, notes, and snippets.

@theSundayProgrammer
Created October 20, 2022 23:26
Show Gist options
  • Save theSundayProgrammer/2db8df455d5c62606276a0aef20f638e to your computer and use it in GitHub Desktop.
Save theSundayProgrammer/2db8df455d5c62606276a0aef20f638e to your computer and use it in GitHub Desktop.
generate all combinations and output result using coroutines
local combo = require "combo"
function print_table(T)
local str=""
for i,v in ipairs(T) do
str = str .. string.format("%d,",v)
end
print(str)
end
for p in combo.combo_gen({1,2,3,4,5,6,7}, 1) do
print_table(p)
end
for p in combo.combo_gen({1,2,3,4,5,6,7}, 4) do
print_table(p)
end
for p in combo.combo_gen({1,2,3,4,5,6,7}, 9) do
print_table(p)
end
[[ solution to Exercise 24.2 from the book:
Programming in Lua - Fourth Edition
by Roberto Ierusalimschy
]]
local M={}
local function get_prefix(T,N)
local result = {}
for i = 1,N do
table.insert(result,T[i])
end
return result
end
local function union(T,S)
local R = {}
for _,v in ipairs(S) do
table.insert(R,v)
end
for _,v in ipairs(T) do
table.insert(R,v)
end
return R
end
local function combo(set, N,K, part_result)
if K == 0 then coroutine.yield(part_result)
elseif N==K then coroutine.yield (union(part_result,get_prefix(set,N)))
else
set[1],set[N] = set[N], set[1]
combo(set, N-1, K, part_result)
combo(set, N-1, K-1,union(part_result,{set[N]}))
set[1],set[N] = set[N], set[1]
end
end
function M.combo_gen(set, K)
if K <= #set then
local co = coroutine.create( function()
combo(set, #set, K, {})
end)
return function ()
local code,res = coroutine.resume(co)
return res
end
else
return function() return nil end
end
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment