Reputation: 1122
I am trying to understand a recursive function.
here it is
let printAllCombinations = (arr, n, r) => {
let data = new Array(r);
arrayCalcuator(arr, data, 0, n - 1, 0, r);
};
// arr === array, data === tempArray, start === start Index, end === end Index, index == current index, r = size of combination
let arrayCalcuator = (array, data, start, end, index, r) => {
console.log("before calcualtor");
if (index === r) {
for (let j = 0; j < r; j++) {
// console.log('do something');
}
}
for (let i = start; i <= end && end - i + 1 >= r - index; i++) {
console.log(array, i, array[i]);
data[index] = array[i];
arrayCalcuator(array, data, i + 1, end, index + 1, r);
}
console.log("after calcualtor, exit the loop?");
};
printAllCombinations([5, 2, 3, 4], [5, 2, 3, 4].length, 3);
in the second for loop. I got the console like this. I am not understanding because in the code I clearly see that there is no code to decrease the i
value. What am I missing here?
[ 5, 2, 3, 4 ] 0 5
[ 5, 2, 3, 4 ] 1 2
[ 5, 2, 3, 4 ] 2 3
[ 5, 2, 3, 4 ] 3 4
[ 5, 2, 3, 4 ] **3** 4
// how the number 3 goes to 2 I don't undershirt
[ 5, 2, 3, 4 ] **2** 3
[ 5, 2, 3, 4 ] 3 4
[ 5, 2, 3, 4 ] 1 2
[ 5, 2, 3, 4 ] 2 3
[ 5, 2, 3, 4 ] 3 4
Upvotes: 1
Views: 66
Reputation: 14423
First, look at the loop condition:
i <= end && end - i + 1 >= r - index
i
is start
, so it goes from start
to end
. The second condition basically just does an adjusted end + 1 >= r
.
Now, on the recursive call:
arrayCalcuator(array, data, i + 1, end, index + 1, r);
i + 1
is start
and index + 1
is the index
parameters, respectively. So that just starts another loop with i
using "starting" at +1.
So...
4
is bigger than the end, so no recursive call is done.i = 4
which fails for the same reason, so loop ends.i = 3
which starts a whole new stack of calls which will also fail to loop on the next call because i
would be bigger than end
(e.g. 4
again). It continues the loop once more and it exits for the same reasons.i = 2
, starts a new call stack which this time will loop.i = 3
.And I think I already made the point here of why your log goes up and then down and then up.
If I were to print the stack:
0
1
2
3
3
2
3
1
2
3
Upvotes: 1