Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all (number of) combinations of an array

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!

like image 894
Cem Avatar asked May 13 '21 06:05

Cem


People also ask

How do you get all possible number combinations?

In fact, if you know the number of combinations, you can easily calculate the number of permutations: P(n,r) = C(n,r) * r! . If you switch on the advanced mode of this combination calculator, you will be able to find the number of permutations.

How do you print all array combinations in Python?

Method 1 (Fix Elements and Recur) We first fix 1 at index 0 in data[], then recur for remaining indexes, then we fix 2 at index 0 and recur. Finally, we fix 3 and recur for remaining indexes. When number of elements in data[] becomes equal to r (size of a combination), we print data[].


Video Answer


2 Answers

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));
like image 123
Robby Cornelissen Avatar answered Oct 25 '22 15:10

Robby Cornelissen


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('|'));
like image 36
A1rPun Avatar answered Oct 25 '22 17:10

A1rPun