问题描述
我在javascript中有n个不同元素的数组,我知道有n个!对这些元素进行排序的可能方法.我想知道生成该数组所有可能排序的最有效(最快)算法是什么?
I have an array of n different elements in javascript, I know there are n! possible ways to order these elements. I want to know what's the most effective (fastest) algorithm to generate all possible orderings of this array?
我有这个代码:
var swap = function(array, frstElm, scndElm) {
var temp = array[frstElm];
array[frstElm] = array[scndElm];
array[scndElm] = temp;
}
var permutation = function(array, leftIndex, size) {
var x;
if(leftIndex === size) {
temp = "";
for (var i = 0; i < array.length; i++) {
temp += array[i] + " ";
}
console.log("---------------> " + temp);
} else {
for(x = leftIndex; x < size; x++) {
swap(array, leftIndex, x);
permutation(array, leftIndex + 1, size);
swap(array, leftIndex, x);
}
}
}
arrCities = ["Sidney", "Melbourne", "Queenstown"];
permutation(arrCities, 0, arrCities.length);
而且它有效,但我想交换每个项目以获得组合在内存方面有点昂贵,我认为这样做的一个好方法是只关注数组的索引并获取数字的所有排列,我想知道是否有一种方法可以计算所有这些而不必切换数组中的元素?我想递归可以得到所有这些,我需要帮助.
And it works, but I guess swapping every item to get the combinations is a bit expensive memory wise, I thought a good way of doing it is just focusing on the indexes of the array and getting all the permutations of the numbers, I'm wondering if there's a way of computing all of them without having to switch elements within the array? I guess recursively is possible to get all of them, I need help to do so.
例如,如果我有:
arrCities = ["Sidney", "Melbourne", "Queenstown"];
我希望输出为:
[[012],[021],[102],[120],[201],[210]]
或:
[[0,1,2],
[0,2,1],
[1,0,2],
[1,2,0],
[2,0,1],
[2,1,0]]
我正在阅读:http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
但维基百科从来都不擅长解释.我不是很懂,我不得不说我的数学水平不是最好的.
But Wikipedia has never been good at explaining. I don't understand much of it, I have to say my math level isn't the best.
推荐答案
这个函数,perm(xs)
,返回给定数组的所有排列:
This function, perm(xs)
, returns all the permutations of a given array:
function perm(xs) {
let ret = [];
for (let i = 0; i < xs.length; i = i + 1) {
let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));
if(!rest.length) {
ret.push([xs[i]])
} else {
for(let j = 0; j < rest.length; j = j + 1) {
ret.push([xs[i]].concat(rest[j]))
}
}
}
return ret;
}
console.log(perm([1,2,3]).join("\n"));
这篇关于生成 JavaScript 数组的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!