Javascript中的排列 [英] permutations in Javascript
问题描述
我正在尝试使用Javascript编写一个函数,该函数可以返回递归的数目,并且还使用递归方法显示字符串的所有排列(假设重复了非字符).我已经看到很多使用for
循环的方法,但是有没有办法我可以不使用获得相同的结果呢?
I'm trying to write a function in Javascript that can return the number of permutations, and also show all the permutations of a string (suppose that non of the character is repeated) using recursive methods. I've seen a lot using for
loop, but is there a way that I can obtain the same outcome without using it?
关于排列的数量,这是我尝试不使用for
循环
For the number of permutations, here is my attempt without using for
loop
var permutation = function (s) {
var fac = function (t) {
if (t === 0) return 1;
return t*fac(t-1);
};
return fac(s.length);
};
它运作良好,但是我不知道如何继续排列列表. 感谢您的帮助!
It works well, but I don't know how to continue with the list of permutations. Thanks for the help!
推荐答案
这是一个无需循环即可在JavaScript中进行排列的函数.
Here's a function to do permutations in JavaScript without loops.
像这样使用它:
let stra = [..."string"].sort(); // first sort your items in an array
while(nextPermutation(stra)) console.log(stra); // keep going until false
function nextPermutation(array, first = 0, last = array.length-1) {
if(first>=last){
return false;
}
let i = last;
function reverse(i, j){
if(i>=j) return;
[array[j], array[i]] = [array[i], array[j]];
reverse(++i, --j);
}
return (function _(){
const i1 = i;
if(array[--i]<array[i1]){
let i2 = last+1;
(function decrement(){
if(array[i] >= array[--i2]) decrement();
})();
[array[i], array[i2]] = [array[i2], array[i]];
reverse(i1, last);
return true;
}
if(i===first){
reverse(first, last);
return false;
}
return _();
})();
}
这篇关于Javascript中的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!