派生数组中每个可能的元素组合

时间:2014-11-27 18:32:07

标签: javascript arrays algorithm sorting combinations

给定一个数组和一个长度,我想得到特定长度的每个可能的元素组合(非重复)。

给定一个数组:

arr = ['a','b','c','d']

并且长度为3,我在输出二维数组的函数之后,如下所示:

result = [
    ['a','b','c'],
    ['b','c','a'],
    ['c','a','b'],
    . . . etc.
]

我已经尝试过解决这个问题并且遇到了一些困难。

1 个答案:

答案 0 :(得分:1)

以下代码使用暴力方法。它生成所需长度的每个组合的每个排列。根据字典检查排列,以避免在结果中重复它们。



function makePermutations(data, length) {
  var current = new Array(length), used = new Array(length),
      seen = {}, result = [];
  function permute(pos) {
    if (pos == length) {      // Do we have a complete combination?
      if (!seen[current]) {   // Check whether we've seen it before.
        seen[current] = true; // If not, save it.
        result.push(current.slice());
      }
      return;
    }
    for (var i = 0; i < data.length; ++i) {
      if (!used[i]) {         // Have we used this element before?
        used[i] = true;       // If not, insert it and recurse.
        current[pos] = data[i];
        permute(pos+1);
        used[i] = false;      // Reset after the recursive call.
      }
    }
  }
  permute(0);
  return result;
}

var permutations = makePermutations(['a', 'a', 'b', 'b'], 3);
for (var i = 0; i < permutations.length; ++i) {
  document.write('['+permutations[i].join(', ')+']<br />');
}
&#13;
&#13;
&#13;