Hi @Tahtoh! Don’t worry, recursion is rarely trivial. Often the trick is to reduce the problem to one or more sub-problems which are small enough to be solved directly; in the case of the one you’ve linked that would be r = 1:
var array = [1, 2, 3, 4, 5];
var r = 1;
function combi(array, r) {
if (r === 1) {
// Simply output each element
for (var i = 0; i < array.length; i++) {
console.log(array[i]);
}
}
}
combi(array, r);
// Output:
// 1
// 2
// 3
// 4
// 5
(I’m writing in JavaScript here; hope that’s okay.)
Now we can take into account the recursion. Usually the problem is not as trivial; but for now we can pretend it is and already got the more complex part from the recursion:
function combi(array, r, result) {
// If there is a result availabe, insert
// a separating space
result = result ? result + ' ' : '';
if (r === 1) {
for (var i = 0; i < array.length; i++) {
// Log the result we got earlier and append
// the solution of the trivial problem
console.log(result + array[i]);
}
}
}
// A function call within the recursion might thus
// look like e.g.
combi([3, 4, 5], 1, '2');
// Which would output:
// 2 3
// 2 4
// 2 5
Now comes the tricky bit – how do we actually reduce the problem to the trivial one? We need to get to a point where it is; this can be done with a loop here, which recursively calls the function with the respective sub-problem of each element in the array:
function combi(array, r, result) {
// ...
if (r !== 1) {
// We loop through the array and take each element as
// a starting point for the respective sub-problem
for (var j = 0; j <= array.length - r; j++) {
// We call the `combi` function with the remaining
// sub-array from the current position, reducing
// the problem by one (i.e. r - 1) and passing the
// result-so-far plus the current element
combi(arr.slice(j + 1, array.length), r - 1, result + array[j]);
}
}
}
// For array = [1, 2, 3, 4, 5] and r = 2 that would call
combi([2, 3, 4, 5], 1, '1');
combi([3, 4, 5], 1, '2');
combi([4, 5], 1, '3');
This is calling itself until the trivial problem is reached. So putting it together:
function combi(arr, r, result) {
result = result ? result + ' ' : '';
if (r === 1) {
for (var i = 0; i < arr.length; i++) {
console.log(result + arr[i]);
}
} else {
for (var j = 0; j <= arr.length - r; j++) {
combi(arr.slice(j + 1, arr.length), r - 1, result + arr[j]);
}
}
}
combi([1, 2, 3, 4, 5], 2);
This is the basic approach how I’d try to find a solution. But there’s no hard and fast answer how to get there; actually, practice is crucial to get the hang of it IMHE. Just don’t give up to quickly! :-)