I want to list all the possible parameter combinations. I wrote a recursive algorithm that should solve the problem. The issue is that the variables I use as the recurive parameters does not keep their old values before the recursive calls.
The problem
Let's say I have 2 parameters with the following possible values:
P1 = A or B
P2 = C or D or E
I want to find the possible combinations:
AC
AD
AE
BC
BD
BE
The recursive "solution"
var params = [];
var param1 = ['A', 'B', 'C'];
var param2 = ['E', 'F'];
var param3 = ['G', 'H', 'I'];
params.push(param1);
params.push(param2);
params.push(param3);
function r(ps, s) {
console.log(ps.length + " " + s.length);
if (ps.length == 0) {
console.log(s);
return;
}
var p = ps[0];
for (idx in p) {
s.push(p[idx]);
console.log("Before call " + s);
r(ps.slice(1), s);
}
}
var sol = [];
r(params, sol);
The runtime issue
When running the program, the s variable keeps growing. The first 3 iterations gives:
Before call A
Before call A, E
Before call A, E, G
After the first call to return, I expect the s variable to contain AE because it was its value before the call.