I am working on a problem where I have to find all the possible subsets (powerSet) of an array. I am using Recursive backtracking for this. I was playing with the solution to get a feel for how the recursive calls are connected. I am having trouble understanding some parts of it. For example, this is the array from where I want to make subsets.
var arr = ['apple', 'banana', 'orange'];
I am using Javascript. The algorithm is: At each recursive step, I am either including the current element or not.
Here is the solution code:
// Code that works
var makeSubset = function (arr) {
var output = []; // Array for storing all the subsets
var subset = function(arr, soFar, idx) { // Helper function
if (idx >= arr.length) {
output.push([...soFar]);
return;
}
soFar.push(arr[idx]);
subset(arr, soFar, idx + 1);
soFar.pop(); // But this works
subset(arr, soFar, idx + 1);
};
subset(arr, [], 0);
return output;
}
console.log(makeSubset(['apple', 'banana', 'ornage']))
// code that does not work
var makeSubset1 = function (arr) {
var output = []; // Array for storing all the subsets
var subset = function(arr, soFar, idx) { // Helper function
if (idx >= arr.length) {
output.push([...soFar]);
return;
}
soFar.push(arr[idx]);
subset(arr, soFar, idx + 1);
soFar = soFar.slice(0, soFar.length - 1);
subset(arr, soFar, idx + 1);
};
subset(arr, [], 0);
return output;
}
console.log(makeSubset1(['apple', 'banana', 'ornage']))
Now, I have changed the solution a bit to see how it affects. Instead of passing the modified soFar array as arguments, I am changing it outside.
soFar.push(arr[idx);
As I have changed the soFar array, and it is a reference, I undo the changes when considering not including the current element.
soFar = soFar.slice(0, soFar.length - 1);
But the above line does not produce the correct output which the following line does.
soFar.pop();
My question is: Don't they do the same thing here? I understand it has something to do with the reference but I am not understanding where is the problem. Also, any general suggestion while working with reference type data structure like an array in recursion backtracking. Any idea would be greatly appreciated. Here is the code snippet that works: