m个单词数组中n个单词的组合 - Javascript

时间:2017-05-20 21:51:28

标签: javascript

鉴于arr = ['mat','cat','fat']
函数getComb(arr, n = 2),其中n是每个组合必须具有的单词数 预期结果:
垫猫
垫脂
猫胖子 我无法进一步修改下面的代码以获得所需的结果。任何的想法? thx

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

1 个答案:

答案 0 :(得分:0)

我建议节省空间的generator function

&#13;
&#13;
// 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));
&#13;
&#13;
&#13;