Skip to content

Instantly share code, notes, and snippets.

@xiaojue
Created June 7, 2017 09:14
Show Gist options
  • Save xiaojue/56f698eecf28f6228c41b6a9ab251acd to your computer and use it in GitHub Desktop.
Save xiaojue/56f698eecf28f6228c41b6a9ab251acd to your computer and use it in GitHub Desktop.
AMN.js
function combine(a) {
var fn = function(n, src, got, all) {
if (n == 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0; j < src.length; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
};
var all = [];
for (var i = 0; i < a.length; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}
function AMN(A, M, N) {
return combine(A).filter((arr) => {
if (arr.length === M) {
var sum = arr.reduce((p, v) => {
return p + v;
});
return sum === N;
}
return false;
});
}
console.log(AMN([1, 2, 3, 4, 5, 6, 7, 8], 3, 10));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment