FOR MODERATOR:
The question for which this is a supposed duplicate of, does not address a number of issues.
- This question is not about how the operators work per se, but how they function in the algorithm, i.e. why those operators at that point.
- This question also includes the bit-wise comparison '&' operator, which the
other question does not address at all. - The central insight to the answer provided is that by assigning
combinationsCount = 1 << listSize
one turns the iterator 'i' in the loop into a bit vector, which can be tested against a particular 'j' to determine if it should be included in the sum to test.
This is a solution to a variation of the coin change problem, I think. The code works, to the best of my knowledge, but I do not understand how the last if check:
if (i & (1 << j)) {
combinationSum += arr[j];
}
works in this algorithm (see below). I ran into it working through a tutorial. I'd really appreciate any explanation of how that portion of the code works.
UPDATE:
To be clear, I understanding WHAT the operators are doing, i.e. the bit shifting and the bit-wise addition. What I want to know is how they operate within the algorithm.
possibleCombinationSumN(arr, n) {
if (arr.indexOf(n) >= 0) {
return true;
}
if (arr[0] > n) {
return false;
}
if (arr[arr.length - 1] > n) {
arr.pop();
return possibleCombinationSumN(arr, n);
}
var listSize = arr.length, combinationsCount = (1 << listSize)
for (var i = 1; i < combinationsCount; i++) {
var combinationSum = 0;
for (var j = 0; j < listSize; j++) {
if (i & (1 << j)) {
combinationSum += arr[j];
}
}
if (n === combinationSum) {
return true;
}
}
return false;
};