I'm trying to create a recursive version of the following nested loops and to get the same results as the reference code. The example is below.
This is a version on Codepen http://codepen.io/anon/pen/XbQMLv
(The intent of the code is to output only unique combinations of integers from the indexes.)
Original code and output:
var len = 4;
for (var a = 0; a < len; a++) {
for (var b = a + 1; b < len; b++) {
for (var c = b + 1; c < len; c++) {
console.log(a, b, c);
}
}
}
// Outputs:
// 0 1 2
// 0 1 3
// 0 2 3
// 1 2 3
Recursive code and output:
var len = 4;
var end = 3;
var data = [];
var loop = function (index) {
if (index === end) {
console.log(data);
return;
}
for (var i = index; i < len; i++) {
data[index] = i;
loop(i + 1);
}
}
loop(0);
// Outputs:
// [ 0, 1, 2 ]
// [ 0, 2, 3 ]
// [ 1, 3, 2 ]
// [ 2, 3, 3 ]
Not sure what I'm missing here.
endwith the loops?var len = 4; for (var a = 0; a < len; a++) ...