具有置换长度参数的javascript置换生成器 [英] javascript permutation generator with permutation length parameter
问题描述
我在那里看到了一些发电机,但它们都是平方矩阵。例如,你给它一个三个项目的列表,它将假设长度的输出也是三个。但是,我想指定项目和长度。
I've seen a few generators out there but they all make a squared matrix. For example, you give it a list of three items and it'll assume the output of the length is also three. However, I'd like to specify the items and the length.
声音就像一个简单的问题,不能相信没有可用的库。如果那里有一个经过测试的库,我想避免自己写这个。任何建议都会很棒。
Sound like an easy problem can't believe there isn't a library available for it. Would like to avoid writing this myself if there's a tested library out there. Any suggestions would be great.
我发现的例子
var list = 'abc';
perms = permutations(list);
//you cannot define the length
示例
var list = 'abc';
var length = 3;
perms = permutations(list,length);
console.log(perms);
/* output
a,a,a
a,b,c
a,b,a
a,c,a
c,a,a
...
*/
我希望能够更改长度并相应地创建排列
I would like to be able to change length and should create permutations accordingly
length = 2
a,a
a,b
b,b
b,a
length = 4
a,a,a,a
a,a,a,b
....
推荐答案
你可以想象长度为表示插槽的数量。考虑到N是初始列表中的元素数,每个插槽都有N种可能性。因此,给定三个值 [1,2,3]
,您将总计 3 x 3 x 3 = 27
排列。
You can imagine the length as representing the number of slots. Each slot has N possibilities, given that N is the number of elements in your initial list. So given three values [1,2,3]
, you will have a total of 3 x 3 x 3 = 27
permutations.
这是我的尝试。包括评论!
Here's my attempt. Comments included!
var list = [1,2,3];
var getPermutations = function(list, maxLen) {
// Copy initial values as arrays
var perm = list.map(function(val) {
return [val];
});
// Our permutation generator
var generate = function(perm, maxLen, currLen) {
// Reached desired length
if (currLen === maxLen) {
return perm;
}
// For each existing permutation
for (var i = 0, len = perm.length; i < len; i++) {
var currPerm = perm.shift();
// Create new permutation
for (var k = 0; k < list.length; k++) {
perm.push(currPerm.concat(list[k]));
}
}
// Recurse
return generate(perm, maxLen, currLen + 1);
};
// Start with size 1 because of initial values
return generate(perm, maxLen, 1);
};
var res = getPermutations(list, 3);
console.log(res);
console.log(res.length); // 27
这篇关于具有置换长度参数的javascript置换生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!