Here is an iterator which will return the table each time it successfully generates a binary number with excepted number of ones:
function generator(ones, total)
return coroutine.wrap(function()
local num = {}
for i=1,total do num[i] = '0' end
local function step(position, left)
if left == 0 then
coroutine.yield(num)
elseif position > total then
return
else
num[position] = '1'
step(position + 1, left-1)
num[position] = '0'
step(position + 1, left)
end
end
step(1, ones)
end)
end
To use it, just call it in a `for x in` loop:
local count = 0
for n in generator(5, 10) do
print(table.concat(n))
count = count + 1
end
print('Total:', count)
For this small test case, it generates 252 number. For your case, C(25,40) == 40225345056, which is over 40 billion numbers. Would you like to rethink your original problem?