生成单个数组中元素的所有排列

时间:2017-11-16 10:39:03

标签: javascript arrays permutation

我已经看到了几个关于如何在数组中生成所有可能的元素排列的类似问题。但是我很难弄清楚如何编写一个算法来输出不包含在每个排列中的值:

从以下数组开始(包含N个元素):

for k in 1..NumClien loop
    if M.P_Array(k).Key = Key then 
...

得到以下结果:

var array = ["apple", "banana", "lemon", "mango"];

2 个答案:

答案 0 :(得分:0)

这样的事情是否有效(基于Recursively print all permutations of a string (Javascript)):

var this_array = ["apple", "banana", "lemon", "mango"];
function *permute(a, n = a.length) {
  if (n <= 1) yield a.slice();
  else for (let i = 0; i < n; i++) {
    yield *permute(a, n - 1);
    const j = n % 2 ? 0 : i;
    [a[n-1], a[j]] = [a[j], a[n-1]];
  }
}

all_arrays = (Array.from(permute(this_array)));
all_arrays = all_arrays.map(function(element){
	return([element[0]+" not "+element[1]+" not "+element[2]+" not "+element[3], element[0]+" "+element[1]+" not "+element[2]+" not "+element[3], element[0]+" "+element[1]+" "+element[2]+" not "+element[3], element[0]+" "+element[1]+" "+element[2]+" "+element[3]]);
 
    /*this is the area you need to play around with to get whatever combination of "not"s you want. */


})
joined_arrays = all_arrays.join("\n");

  
console.dir(all_arrays); // preserving as array
console.dir(joined_arrays); //if you want as a single block of text

答案 1 :(得分:0)

这种简单的方法使用位掩码,因此它只适用于相对较少的单词。

var array = ["apple", "banana", "lemon", "mango"];

var result = [];
for (var n = 0; n < 1 << array.length; n++) {
	var i, a = [];
	for (i = 0; i < array.length; i++) if ((n & (1 << i)) == 0) a.push(array[i]);
	for (i = 0; i < array.length; i++) if ((n & (1 << i)) != 0) a.push("not " + array[i]);
	result.push(a.join(" "));
}

console.dir(result.join("\n"));