获取数组元素的所有组合 [英] Get all combinations of elements in array
本文介绍了获取数组元素的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一种算法来获得元件的所有可能的组合的值中的多二维数组。类似的东西来置换。
数组中的循环必须是双向的。
例如,
VAR ARR = [[1],[2],[3] [4];
会产生的结果。
[1,2]
[1,3]
[2,3]
[3,4]
[4,3]
[3,2]
[2,1]
解决方案
VAR改编= [1,2,3,4],结果= [];
对于(VAR I = 0; I< arr.length; I + = 1){
对于(VAR J = 0; J< arr.length; J + = 1){
如果(我!== j)条{
result.push([改编[I],编曲[J]);
}
}
}
执行console.log(结果);
输出
[1,2]
[1,3]
[1,4],
[2,1],
[2,3]
[2,4],
[3,1],
[3,2],
[3,4],
[4,1],
[4,2],
[4,3]]
I need an algorithm to get all the possible combinations of elements in a multi dimensional array of values. Something similar to a permutation.
The loop in the array must go both ways.
For example,
var arr= [[1],[2],[3],[4]];
would produce a result of
[1,2]
[1,3]
[2,3]
[3,4]
[4,3]
[3,2]
[2,1]
解决方案
var arr = [1, 2, 3, 4], result = [];
for (var i = 0; i < arr.length; i += 1) {
for (var j = 0; j < arr.length; j += 1) {
if (i !== j) {
result.push([arr[i], arr[j]]);
}
}
}
console.log(result);
Output
[ [ 1, 2 ],
[ 1, 3 ],
[ 1, 4 ],
[ 2, 1 ],
[ 2, 3 ],
[ 2, 4 ],
[ 3, 1 ],
[ 3, 2 ],
[ 3, 4 ],
[ 4, 1 ],
[ 4, 2 ],
[ 4, 3 ] ]
这篇关于获取数组元素的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文