Question: I want to program a counter which is represented by an array of numbers, starting with:

```
[0, 0, 0]

```

The constraint here is, that each position has a different cap, so it's not necessarily 9 or something else, but it is given. For instance:

```
[4, 2, 1]

```

Which would lead to the following incrementation sequence:

```
[0, 0, 0]
[0, 0, 1] 
[0, 1, 0]
[0, 1, 1]
[0, 2, 0]
[0, 2, 1]
[1, 0, 0]
.
.
.

```

Of course I can think of a solution using modulo and adding each carryover onto the next position. But has someone an idea how to implement this efficiently, respectively with nice Ruby syntax without cluttering it too much?

That is my naive implementation:

```
max = [10, 1, 1, 1, 10]
counter = [0, 0, 0, 0, 0]

i = counter.length-1
while counter != max do
   counter[i] = counter[i] + 1
   while counter[i] > max[i]
      counter[i] = 0
      i = i - 1
      counter[i] = counter[i] + 1
   end
   i = counter.length-1
 end

```

Answer: 
I'm not sure about efficiency but here's my shot at it:

```
start = [0, 0, 0]
cap = [4, 2, 1]

start.zip(cap).map{ |i, c| (i..c).to_a }.reduce(&:product).map &:flatten

```

Produces something like:

```
[[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],
 [2, 0, 0],
 [2, 0, 1]...]

```
Create an array for each cap, with values from 0 upto cap. Take the first array and calculate the Cartesian product with the rest of the arrays.

```
caps = [4, 2, 1]
arrs = caps.map{|cap| (0..cap).to_a} #=>[[0, 1, 2, 3, 4], [0, 1, 2], [0, 1]]
p arrs.shift.product(*arrs)
# =>[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [0, 2, 0], [0, 2, 1], ...

```

If you don't want a memory-consuming array with the results, then provide a block. `product` will yield each element to it, one by one.

```
arrs = caps.map{|cap| (0..cap).to_a}
arrs.shift.product(*arrs){|el| puts el.join} #no resulting array
#000
#001
#010
#011
#...

```