Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

javascript - 从长度为6的数组中返回3个组合的所有组合的算法,而数字不出现在同一组数字中-Javascript(Algorithm to return all combinations of 3 combinations from a array of length 6 without the number appearing with the same set of numbers - Javascript)

I was trying to write a algorithm in javascript that returns all the possible 3 digit numbers numbers from a given array of length 6 For Example

(我试图用JavaScript编写一种算法,该算法从长度为6的给定数组返回所有可能的3位数字。)

var arr = [1, 2, 3, 4, 5, 6];

I have already got the combinations with the same sets of numbers in different positions in the 2D array.

(我已经在2D数组中的不同位置获得了具有相同数字集的组合。)

( The code which I took the help of )

(( 我帮助的代码 ))

If I have the same numbers in different combinations then I would like to remove them form the array.

(如果我在不同组合中具有相同的数字,那么我想从数组中删除它们。)

like I have [1, 2, 3] at index i in the array comtaining all the possible combinations then I would like to remove other combination with the same numbers like [2, 1, 3] , [1, 3, 2] and so on..

(就像我在包含所有可能组合的数组的索引i处具有[1, 2, 3]一样,那么我想删除具有相同数字的其他组合,例如[2, 1, 3] 2、1、3 [2, 1, 3][1, 3, 2]和等等..)

Note the array also contains numbers repeated like [3, 3, 3] , [2, 2, 2] , [3, 2, 3] and so on

(请注意,数组还包含重复的数字,例如[3, 3, 3][2, 2, 2][3, 2, 3] ,依此类推)

I expect an 2d array which has the values : [[1,2,3],[1,2,4],[1,2,5],[1,2,6],[1,3,4]] and so on (24 possibilities)

(我期望一个2d array ,其值是: [[1,2,3],[1,2,4],[1,2,5],[1,2,6],[1,3,4]]等(24种可能性))

Is there any way to do this?

(有什么办法吗?)

Thank you!

(谢谢!)

  ask by Karan Gandhi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

 const arr = [1, 2, 3, 4, 5, 6]; const result = arr.reduce((a, v) => arr.reduce((a, v2) => { arr.reduce((a, v3) => { const current = [v, v2, v3].sort().join(","); !a.find(_ => _.sort().join() === current) && a.push([v, v2, v3]); return a; }, a); return a; }, a), []); console.log(result.length); console.log(...result.map(JSON.stringify)); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...