Sometimes I need a way to do this, and wonder if this is a common problem or method and has a name to it:
Such as, we want to iterate through all cases of 4 dice, or iterate through all cases of 20 slots, and each slot can fit in any number from 0 to 50.
So the requirement is given N, the size of the array, such as N = 4, and a "range" such as from 1 to 6, and we do a Iterator.new(4, 1..6)
and get back:
[1, 1, 1, 1]
and have a way to do iterator.next()
and get back
[1, 1, 1, 2]
and keep on doing iterator.next()
will get us
[1, 1, 1, 6]
and the next iterator.next()
will get us
[1, 1, 2, 1]
which is like 6 + 1
and it can't hold it, so it resets to 1
and carry over to the next digit.
and iterator.next()
will finally get to
[6, 6, 6, 6]
and the next iterator.next()
will get us
false (or nil)
Does this problem have a common name in computer science, and what might be a simple way to do it in Ruby?
Right now I am trying to do it using recursion, and it seems complicated:
n = 4
a = 1
b = 6
arr = [a] * 4
def increment_position(arr, a, b, pos)
return false if (pos >= arr.length)
arr[-1 - pos] += 1
if arr[-1 - pos] > b
arr[-1 - pos] = a
return increment_position(arr, a, b, pos + 1)
else
return arr
end
end
def get_next_iteration(arr, a, b)
return increment_position(arr, a, b, 0)
end
loop do
p arr
break if !get_next_iteration(arr, a, b)
end
P.S. The solution should not use too much memory, such as just bytes, or kilobytes, or MB. For example, it should be able to handle Iterator.new(5, 0..50)
or Iterator.new(6, 0..50)
easily.