1

Given arr = ['mat','cat','fat']
A function getComb(arr, n = 2) where n is the number of words each combination must have.
Expected results:
mat cat
mat fat
cat fat
I could not modify the code below any further to get the desired results. Any idea? thx

Thanks to Knskan3:

'getCombinations': (arr, n) => {
      let i, j, k, elem, l = arr.length, childperm, ret = [];
      if (n === 1) {
        for (let i = 0; i < arr.length; i++) {
          ret.push([arr[i]]);         
        }
        return ret;
      }
      else {
        for (i = 0; i < l; i++) {
          elem = arr.shift();
          for (j = 0; j < elem.length; j++) {
            childperm = lib.getCombinations(arr.slice(), n - 1);
            for (k = 0; k < childperm.length; k++) {
              ret.push([elem[j]].concat(childperm[k]));
            }
          }
        }
        return ret;
      }
    },
Community
  • 1
  • 1
Fred J.
  • 5,759
  • 10
  • 57
  • 106
  • Does order matter? Given ['cat','mat'] would you expect output with n===2 of just ['cat mat'] or ['cat mat', 'mat cat']? – Paul May 20 '17 at 22:09
  • Order does not mater for combination. It only maters for permutations which is not the case here. :) – Fred J. May 20 '17 at 22:55

1 Answers1

0

I suggest a space-efficient generator function:

// Generate all k-combinations of first n array elements:
function* combinations(array, k, n = array.length) {
  if (k < 1) {
    yield [];
  } else {
    for (let i = --k; i < n; i++) {
      for (let combination of combinations(array, k, i)) {
        combination.push(array[i]);
        yield combination;
      }
    }
  }
}

// Example:
console.log(...combinations(['mat', 'cat', 'fat'], 2));
le_m
  • 19,302
  • 9
  • 64
  • 74
  • Is there some reason you are not using `yield *combinations(array, k, i)` instead of the loop? –  May 21 '17 at 02:17
  • How can I assign the results to a variable? `y=...combinations(['mat', 'cat', 'fat'], 2)` gives "Uncaught SyntaxError: Unexpected token ..." – Fred J. May 21 '17 at 06:47
  • @torazaburo The recursive call to `combinations` produces sub-combinations of length k-1 - see the somewhat unreadable `--k` in the loop initializer. I still need to append one element before `yield`-ing them. A `yield*` doesn't allow me to do that. – le_m May 21 '17 at 12:04