简体   繁体   中英

Combinations of n words from array of m words - Javascript

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;
      }
    },

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)); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM