使用Javascript / jQuery的:如何从一个数组的项目得到排列?
如果我有一个数组,其中包含的项目,例如:
If I have one array that contains items , for example
["To","Ti","Ta"]
我想有返回数组中追加项目的所有排列功能,在此功能将返回:
I would like to have a function that return all permutations of appended items in array, here function would return:
[["ToTiTa"]["ToTaTi"]["TiToTa"]["TiTaTo"]["TaToTi"]["TaTiTo"]]
你能帮助我吗?
Could you help me please?
你在寻找什么是置换。您可以用递归函数来创建它们。
What you are looking for are permutations. You can create them with a recursive function.
下面的code是一个例子。 置换
是前端功能,您的code应该调用。 permute_rec
是递归函数,建立置换阵列和交换
仅仅是一个方便的功能,在数组交换的元素:
The code below is an example. permute
is the front-end function, which your code should call. permute_rec
is the recursive function that builds the permutation array and swap
is just a convenience function for swapping elements in an array:
function swap(array, i, j) {
if (i != j) {
var swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
function permute_rec(res, str, array) {
if (array.length == 0) {
res.push(str);
} else {
for (var i = 0; i < array.length; i++) {
swap(array, 0, i);
permute_rec(res, str + array[0], array.slice(1));
swap(array, 0, i);
}
}
}
function permute(array) {
var res = [];
permute_rec(res, "", array);
return res;
}
console.log(permute(["A", "B", "C"]));
修改:您可以扩展此code包括子阵与此code的排列:
Edit: You can extend this code to include permutations of subarrays with this code:
function xpermute_rec(res, sub, array) {
if (array.length == 0) {
if (sub.length > 0) permute_rec(res, "", sub);
} else {
xpermute_rec(res, sub, array.slice(1));
xpermute_rec(res, sub.concat(array[0]), array.slice(1));
}
}
function xpermute(array) {
var res = [];
xpermute_rec(res, [], array);
return res;
}
console.log(xpermute(["A", "B", "C"]));
这code创建的所有子阵列,然后使用原来的code创建的排列。 (空数组的情况下被忽略。)
This code creates all subarrays and then uses the original code to create the permutations. (The case of the empty array is skipped.)