派生在数组元素的每个可能的组合 [英] Derive every possible combination of elements in array
本文介绍了派生在数组元素的每个可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定的阵列和一个长度,我想派生元素的每个可能的组合(不重复)的特定的长度。
所以,给出的数组:
改编= ['一','B','C','D']
和长度为3,我认为如下输出一个2维数组的函数之后很
的结果= [
['一','B','C'],
['B','C','一个'],
['出租车'],
。 。 。等等
]
我试着解决这个和有困难的交易。
解决方案
以下code使用蛮力的方法。它产生所需长度的每个组合的每个排列。排列是核对字典,以避免重复的结果他们。
\r
\r\r
\r 函数makePermutations(数据长度){\r
VAR电流=新阵列(长度),用来=新阵列(长度)\r
可见= {},结果= [];\r
功能置换(POS){\r
如果(POS ==长度){//我们有一个完整的组合?\r
如果(!见到[电流]){//检查我们是否已经看到过。\r
看到[当前] =真; //如果不是,将其保存。\r
result.push(current.slice());\r
}\r
返回;\r
}\r
对于(VAR I = 0; I< data.length ++我){\r
如果(!使用[I]){//我们以前使用这个元素?\r
使用[I] = TRUE; //如果没有,将其插入和递归。\r
电流[POS] =数据[I]\r
置换(正+ 1);\r
使用[I] = FALSE; //重置递归调用后。\r
}\r
}\r
}\r
置换(0);\r
返回结果;\r
}\r
\r
变种置换= makePermutations(['一','一个','B','B'],3);\r
对于(VAR I = 0; I< permutations.length ++我){\r
的document.write('['+排列[I]。加入(,)+]所述峰; br />');\r
}
\r
Given an array and a length, I want to derive every possible combination of elements (non-repeating) at the specific length.
So given an array of:
arr = ['a','b','c','d']
and a length of 3, I'm after a function that outputs a 2-dimensional array as follows:
result = [
['a','b','c'],
['b','c','a'],
['c','a','b'],
. . . etc.
]
I've tried tackling this and have had a deal of difficulty.
解决方案
The following code uses a brute-force approach. It generates every permutation of every combination of the desired length. Permutations are checked against a dictionary to avoid repeating them in the result.
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 />');
}
这篇关于派生在数组元素的每个可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文