I implemented Donald Knuth’s “Algorithm M” for generating all numbers in a mixed-radix numbering system. I would like to turn this into an iterator so I could loop over all of them but without having them all in memory at the same time.
Here’s a simple case with the code:
m = [1,2,1]
nl = length(m)
a = zeros(Int,nl)
while true
j = nl
println(a)
while true
if a[j] < m[j] break; end
a[j] = 0
j -= 1
if j==0 break; end
end
if j == 0 break; end
a[j] += 1
end
What I would like is something like this:
for i in MyMixedRadix([1,2,1])
# code goes here
end
How do I turn my nested for
loops into an iterator?
PS Here’s the output from the example:
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
[0, 1, 1]
[0, 2, 0]
[0, 2, 1]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[1, 1, 1]
[1, 2, 0]
[1, 2, 1]