具有排列长度参数的javascript排列生成器

我已经看到了几个发电机,但他们都做了一个平方matrix。 例如,你给它一个三个项目的列表,它会假设长度的输出也是三个。 但是,我想指定项目和长度。

听起来像一个简单的问题,不能相信没有可用的图书馆。 如果在那里有一个testing过的库,想避免自己写这个。 任何build议将是伟大的。

我发现的例子

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 ... */ 

我希望能够改变长度,并相应地创build排列

 length = 2 a,a a,b b,b b,a length = 4 a,a,a,aa,a,a,b .... 

你可以想象长度代表插槽的数量。 每个插槽有N个可能性,因为N是您的初始列表中元素的数量。 所以给定三个值[1,2,3] ,总共将有3 x 3 x 3 = 27个排列。

这是我的尝试。 包括评论!

 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 

小提琴

我写了一个小型的库,使用生成器给你自定义项目和元素数量的排列。 https://github.com/acarl005/generatorics

 const G = require('generatorics') for (let perm of G.permutation(['a', 'b', 'c'], 2)) { console.log(perm); } // [ 'a', 'b' ] // [ 'a', 'c' ] // [ 'b', 'a' ] // [ 'b', 'c' ] // [ 'c', 'a' ] // [ 'c', 'b' ] 

有点晚了,但也许这会帮助别人。 它允许重复,长度说明:)

 function samplePermutation(sequence, repetition = false, n = null) { if (sequence.constructor !== Array) { throw new Error("samplePermutation: sequence needs to be an array."); } if (n === null) { n = sequence.length; } var permutation = []; var add; while ((repetition && (permutation.length < n)) || ((!repetition) && (sequence.length))) { var index = Math.floor(Math.random() * sequence.length); if (repetition) { add = sequence[index]; } else { add = sequence.splice(index, 1); } permutation = permutation.concat(add); } return (permutation); } 
Interesting Posts