I have been trying to accomplish this since yesterday, though no luck yet. I have found solutions where there always is a slight difference in what I want to accomplish.
I am trying to get all possible combinations, slightly like this: combination_k , but I also want the same items to pair up with itself, so given the following:
input [1, 4, 5]
and 2
(number of combinations) should return:
[1, 1], [1, 4], [1, 5], [4, 4], [4, 5], [5, 5]
input [1, 4, 5]
and 3
should return:
[1, 1, 1], [1, 1, 4], [1, 1, 5], [1, 4, 4], [1, 4, 5], [4, 4, 4], [4, 4, 5], [5, 5, 5], [5, 5, 4], [5, 5, 1]
(The order is not important).
I have been adjusting combination_k, it got me far enough that it worked with 2 but it didn't work when I provided 3 as a parameter.
const combinations = getAllCombinations([1, 4, 5], 2);
// combinations = [1, 1], [1, 4], [1, 5], [4, 4], [4, 5], [5, 5]
Any tips are welcome!
The problem is commonly referred to as k-combinations with repetitions .
Here's a solution that relies on recursion to get the desired result:
const combinations = (array, r) => { const result = []; const fn = (array, selected, c, r, start, end) => { if (c == r) { result.push([...selected]); return; } for (let i = start; i <= end; i++) { selected[c] = array[i]; fn(array, selected, c + 1, r, i, end); } } fn(array, [], 0, r, 0, array.length - 1); return result; } console.log(combinations([1, 4, 5], 3));
A modified version of the code you provided:
function getAllCombinations(arr, n) { if (n <= 0) return []; if (n === 1) return [...arr]; return arr.reduce((acc, cur, i) => { const head = arr.slice(i, i + 1); const combinations = getAllCombinations(arr.slice(i), n - 1).map(x => head.concat(x)); return [...acc, ...combinations]; }, []); } console.log(getAllCombinations([1, 4, 5], 2).join('|')); console.log(getAllCombinations([1, 4, 5], 3).join('|'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.