Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Last active December 10, 2015 12:09
Show Gist options
  • Select an option

  • Save hughfdjackson/4432560 to your computer and use it in GitHub Desktop.

Select an option

Save hughfdjackson/4432560 to your computer and use it in GitHub Desktop.
var uniqWith = function(arr, fn){
return arr.reduce(function(a, item){
if ( a.some(fn.bind(null, item)) ) return a
a.push(item)
return a
}, [])
}
var arrEq = function(arr1, arr2){
return arr1.every(function(val, i){ return val === arr2[i] })
}
// stolen from http://stackoverflow.com/questions/9960908/permutations-in-javascript
function permute(input) {
var permArr = [],
usedChars = [];
function main(input){
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
main(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr;
}
return main(input);
}
var allLengths = function(arr){
return arr.map(function(v, i){
return arr.slice(i)
})
}
var flatten = function(arr){
return arr.reduce(function(arr, v){
return arr.concat(v)
}, [])
}
var allCombos = function(arr){
return flatten(permute(arr).map(allLengths))
}
var sum = function(ns){
return ns.reduce(function(a, b){ return a + b })
}
var allAddUp = function(res){
var ns = [].slice.call(arguments, 1),
combos = allCombos(ns)
var res = combos.filter(function(ns){
return sum(ns) == res
})
var sorted = res.map(function(arr){ return arr.sort() })
return uniqWith(sorted, arrEq)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment