Question: I have a scenario to get a output like the following.

```
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

```

When the input is 3 it would give 8 combinations as above. If the input is 4, there would be 16 combinations. I am able to achieve this using nested for loop as below.

```
value1 = 2, value2 = 2, value3 = 2;
my function () {
    for(var i = 0; i<this.value1; i++) { 
      for(var j = 0; j < this.value2; j++) { 
        for(var k = 0; k < this.value3; k++) { 
           console.log(i,j,k);
        }
      }
    }
}

```

This is fine if it is for input 3, But I have to get the output for input 10. So I need to write 10 nested for loops as above. I know it is bad practice, I don't know how to use the recursive here. Please help me on this.

Answer: 
Here is a recursive function that can do the required job.

```js
function solveUtil(limits, index, cur) {
    if (index === limits.length) {
        console.log(cur.join(' '));
    } else {

        for (let i = 0; i < limits[index]; i++) {
            cur.push(i);
            solveUtil(limits, index + 1, cur);
            cur.pop();
        }
    }
}

function solve(limits) {
    solveUtil(limits, 0, []);
}

solve(new Array(10).fill(2));
```
You could use a [`Generator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator) with [`function*`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) and take the combination on the fly.

```js
function* binary(length, array = []) {
    if (--length) {
        yield* binary(length, [...array, 0]);
        yield* binary(length, [...array, 1]);
    } else {
        yield [...array, 0];
        yield [...array, 1];
    }
}

[...binary(3)].map(a => console.log(...a));
```

```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```