Skip to content

Instantly share code, notes, and snippets.

@alesmenzel
Last active August 28, 2018 20:40
Show Gist options
  • Save alesmenzel/80b78c374921cff419d0324aa299e9d3 to your computer and use it in GitHub Desktop.
Save alesmenzel/80b78c374921cff419d0324aa299e9d3 to your computer and use it in GitHub Desktop.
Combination of k elements from an array
const k_combinations = (arr, k) => {
if (arr.length < k) {
return [];
}
if (arr.length === k) {
return [arr];
}
if (k === 1) {
return arr.map(i => [i]);
}
const res = [];
for (let i = 0; i < arr.length; i++) {
const combinations = k_combinations(arr.slice(i + 1), k - 1);
for (let j = 0; j < combinations.length; j++) {
res.push([arr[i], ...combinations[j]]);
}
}
return res;
}
const arr = ['a', 'b', 'c', 'd', 'e'];
console.log(k_combinations(arr, 1));
// [["a"],["b"],["c"],["d"],["e"]]
console.log(k_combinations(arr, 2));
// [["a","b"],["a","c"],["a","d"],["a","e"],["b","c"],["b","d"],["b","e"],["c","d"],["c","e"],["d","e"]]
console.log(k_combinations(arr, 3));
// [["a","b","c"],["a","b","d"],["a","b","e"],["a","c","d"],["a","c","e"],["a","d","e"],["b","c","d"],["b","c","e"],["b","d","e"],["c","d","e"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment