-
-
Save dachev/1013791 to your computer and use it in GitHub Desktop.
| // Actually, this is not going to work. Please ignore it. | |
| function isMeasurable(target, array) { | |
| if (array.length < 1) { return false; } | |
| if (array.indexOf(target) >= 0) { return true; } | |
| var weights = array.concat(target); | |
| var length = 1 << weights.length; | |
| for (var i = 0; i < length; i++) { | |
| var position = weights.length - 1; | |
| var bitmask = i; | |
| var subset = []; | |
| while(bitmask > 0) { | |
| if((bitmask & 1) == 1) { subset.push(weights[position]); } | |
| position--; | |
| bitmask >>= 1; | |
| } | |
| if (subset.length < 2) { continue; } | |
| if (subset.indexOf(target) < 0) { continue; } | |
| var total = sum(subset); | |
| if (total % 2 == 0 && total/2 >= target) { return true; } | |
| } | |
| return false; | |
| } | |
| function sum(subset) { | |
| var sum = 0; | |
| for (var i = 0; i < subset.length; i++) { sum += subset[i]; } | |
| return sum; | |
| } |
Solve the following problem by iterating over the power-set (non-recursive): Given an array of weights, is it possible to measure the target on a traditional scale. You are allowed to put the weights on either side.
Ah, like finding out the following:
With [1, 2, 4, 8] you can measure targets between 0 and 15 by putting weights on one side and the target on the other side.
With [1, 3, 9] you can measure targets between 0 and 13 by putting weights on both sides and the target on the other side.
Sort of. To be precise:
isMeasurable(8, [5, 6, 9]) => true
isMeasurable(13, [5, 6, 9]) => false
Untested: https://gist.github.com/1021993
Cool, this works :-)
Can you come up with a recursive version?
It worked directly? There wasn't even a typo? Wow...
I'll think about a recursive version.
I've updated my gist with a recursive version (untested).
What are you trying to do?