简体   繁体   English

如何获得一个数组,其中包含另一个数组的 n 个元素的所有可能排列?

[英]How to get an array with all the possible permutations of n elements of another array?

I started studying not so long ago [this is actually my first post] but I decided to try a little side project in javascript and I encountered this challenge.我不久前开始学习 [这实际上是我的第一篇文章] 但我决定在 javascript 尝试一个小项目,我遇到了这个挑战。

I have an array with 7 elements right now, but i plan to change its length in the future.我现在有一个包含 7 个元素的数组,但我计划在将来更改它的长度。 I need another array with all the possible combinations of N elements of the first array.我需要另一个数组,其中包含第一个数组的 N 个元素的所有可能组合。

So far I could only find a way to get all combinations (N = firstArray.length-1), but haven't had any luck with a lower N.到目前为止,我只能找到一种方法来获得所有组合 (N = firstArray.length-1),但没有遇到较低 N 的任何运气。

Can anyone shed some light?任何人都可以阐明一下吗? Thanks!谢谢!

Here is one way to get the answer.这是获得答案的一种方法。 To understand the idea, begin by imagining you want to find all arrangements of an array of two, non-like elements [A,B].要理解这个想法,首先假设您想要找到两个非相似元素 [A,B] 的数组的所有排列。 Do not think of this array as [A,B].不要将此数组视为 [A,B]。 Think of it as [0,1].将其视为 [0,1]。 Since all combinations of these two elements can be found by counting from 0 to 3 in base 2, we have [0,0],[0,1],[1,0] and [1,1].由于这两个元素的所有组合都可以通过以 2 为基数从 0 数到 3 来找到,因此我们有 [0,0]、[0,1]、[1,0] 和 [1,1]。 So counting from 1 to 3 in base two will give you all possible combinations, and if you throw out all the arrays with repeat digits and then substitute back with A for 0 and B for 1, you have your answer.因此,以二为基数从 1 数到 3 将为您提供所有可能的组合,并且如果您将所有带有重复数字的 arrays 丢掉,然后用 A 代替 0,用 B 代替 1,您就有了答案。

So to solve your seven-element problem,所以要解决你的七元素问题,

  1. Declare a variable, say "let allCombinations = []; to store all your possible combinations.声明一个变量,比如“let allCombinations = []; 来存储所有可能的组合。

  2. Work in base seven and make the computer count from [0,0,0,0,0,0,0] to [6,6,6,6,6,6,6] by base seven.以七为基数工作,让计算机以七为基数从 [0,0,0,0,0,0,0] 计数到 [6,6,6,6,6,6,6]。

  3. Check each new base-seven array for any repeat numbers using a loop from 0 to six to check each element in the array to see if it occurs more than once.使用从 0 到 6 的循环检查每个新的以七为基数的数组是否有任何重复数字,以检查数组中的每个元素是否出现多次。

  4. If elements occur more than once in the current array, toss it out.如果元素在当前数组中出现不止一次,则将其丢弃。 If not, push it to allCombintation.如果不是,则将其推送到 allCombination。

  5. Continue this process until you reach [6,6,6,6,6,6,6].继续此过程,直到到达 [6,6,6,6,6,6,6]。 Then map through the arrays and replace each digit with its corresponding original element.然后 map 到 arrays 并用其对应的原始元素替换每个数字。

This process can be modified to account for sets with repeat element as well.可以修改此过程以考虑具有重复元素的集合。 But the basic problem this approach solves is ensuring every possible arrangement of elements is accounted for without missing any arrangements.但这种方法解决的基本问题是确保元素的每一种可能排列都得到考虑,而不会遗漏任何排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM