获取多维数组的N个元素的所有组合

编程入门 行业动态 更新时间:2024-10-25 21:19:48
本文介绍了获取多维数组的N个元素的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个算法来获取M个元素的多维数组中N个元素的所有可能组合。

I'm trying to write an algorithm to get all the possible combinations of N elements inside a multi dimensional array of M elements.

类似于:

function getCombinations(arr, n){ ... } var arr = [ ["A"],["B","C"],["D","E"]]; var n = 2; getCombinations(arr,n);

这应该产生:

[ ["A","B"],["A","C"],["A","D"],["A","E"], ["B","D"],["B","E"], ["C","D"],["C","E"] ]

数组中的元素数量可能会有所不同,唯一设置的是数字组合的元素。

The number of elements inside the array may vary, the only thing set is the number of elements of the combinations.

顺序没关系,但你不能重复,我的意思是 [A,B] = = [B,A] ,所以第二个没有考虑。

The order doesn't matter but you cannot repeat, I mean ["A","B"] == ["B","A"], so the second one is not take in consideration.

任何帮助?

推荐答案

ChrisB解决方案有一个错误,他没有在arr.shift之前追逐循环的长度,它是没有返回最后一个组合,所以我认为这将完成这项工作:

ChrisB solution had a mistake, he wasn't chaching the length of the loop before the arr.shift, and it was not returning the last combination, so I think this will do the job:

function getCombinations(arr, n){ var i,j,k,elem,l = arr.length,childperm,ret=[]; if(n == 1){ for(var i = 0; i < arr.length; i++){ for(var j = 0; j < arr[i].length; j++){ ret.push([arr[i][j]]); } } return ret; } else{ for(i = 0; i < l; i++){ elem = arr.shift(); for(j = 0; j < elem.length; j++){ childperm = getCombinations(arr.slice(), n-1); for(k = 0; k < childperm.length; k++){ ret.push([elem[j]].concat(childperm[k])); } } } return ret; } i=j=k=elem=l=childperm=ret=[]=null; } getCombinationss([["A"],["B"],["C","D"]], 2); //[["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"]] getCombinationss([["A"],["B"],["C"],["D"]], 2); //[["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]

更多推荐

获取多维数组的N个元素的所有组合

本文发布于:2023-11-29 18:31:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   组合   数组   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!