For instance, this is 5 choose 2:
var array = [0,1,2,3,4];
var result = array.flatMap(
(v, i) => array.slice(i+1).map(w => [v, w])
);
console.log(result);
How would I be able to do 5 choose 3 using this method?
For instance, this is 5 choose 2:
var array = [0,1,2,3,4];
var result = array.flatMap(
(v, i) => array.slice(i+1).map(w => [v, w])
);
console.log(result);
How would I be able to do 5 choose 3 using this method?
Just add another level of nesting:
var array = [0,1,2,3,4];
var result = array.flatMap((v, i) =>
array.slice(i+1).flatMap((w, j) =>
array.slice(i+1+j+1).map(u =>
[v, w, u]
)
)
);
console.log(result);
At this point, it might be easier to do with recursion though:
function choose(arr, k, prefix=[]) {
if (k == 0) return [prefix];
return arr.flatMap((v, i) =>
choose(arr.slice(i+1), k-1, [...prefix, v])
);
}
console.log(choose([0,1,2,3,4], 3));
choose
also works with string values (or really anything). Use choose(["ab","cd","ef","gh"],3).map(c => c.join(''))
. You could build a string-specific version of choose
as well that uses string concatenation instead of array consing. –
Virility [ "AABBCC"]
when given an array of AA,BB,CC –
Anthesis © 2022 - 2024 — McMap. All rights reserved.