Home > Blockchain >  Generating all combinations of elements in a single array (for cominations of N elements)
Generating all combinations of elements in a single array (for cominations of N elements)

Time:10-19

I'm trying to build/find a function, which will give me all combinations for N number of elements.

The solution below gives me an answer for pairs (i.e. 2 elements).

I'd like to parameterize it, so that I can define the number of combined elements (e.g. 3 elements => ['one', 'two', 'three'], ['one', 'two', 'four'], ... , 4 elements, and so on.

(Bonus internet points if you can tell me the name what I'm looking for (cartesian-product?)!)

var array = ['one', 'two', 'three', 'four', 'five']

// get pairs
var result = array => array.flatMap((v, i) => array.slice(i 1).map( w => [v, w] ));

console.log(result(array))

// output:
// [
//  ["one", "two"],
//  ["one", "three"],
//  ["one", "four"],
//  ["one", "five"],
//  ["two", "three"],
//  ["two", "four"],
//  ["two", "five"],
//  ["three", "four"],
//  ["three", "five"],
//  ["four", "five"]
// ]

CodePudding user response:

Solution is

var array = ['one', 'two', 'three', 'four', 'five']

var combine = function(a, min) {
    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);
        }
        return;
    }
    var all = [];
    for (var i = min; i < a.length; i  ) {
        fn(i, a, [], all);
    }
    all.push(a);
    return all;
}

console.log(combine(array, 2))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I think this is your solution.

/** 
 * Usage Example:
 * 
 * console.log(combination(['A', 'B', 'C', 'D'], 2, true)); // [[ 'A','A' ], [ 'A', 'B' ]...] (16 items)
 * console.log(combination(['A', 'B', 'C', 'D'])); // [['A', 'A', 'A', 'B' ],.....,['A'],] (340 items)
 * console.log(comination(4, 2)); // all posible values [[ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 0, 0 ], [ 0, 1 ], [ 0, 2 ]...] (20 items)
 */
function combination(item, n) {
  const filter = typeof n !=='undefined';
  n = n ? n : item.length;
  const result = [];
  const isArray = item.constructor.name === 'Array';

  const pow = (x, n, m = []) => {
    if (n > 0) {
      for (var i = 0; i < 4; i  ) {
        const value = pow(x, n - 1, [...m, isArray ? item[i] : i]);
        result.push(value);
      }
    }
    return m;
  }
  pow(isArray ? item.length : item, n);

  return filter ? result.filter(item => item.length == n) : result;
}

console.log("#####first sample: ", combination(['A', 'B', 'C', 'D'], 2)); // with filter
console.log("#####second sample: ", combination(['A', 'B', 'C', 'D'])); // without filter
console.log("#####third sample: ", combination(4, 2)); // just number
  • Related