javascript permutation generator with permutation length parameter

后端 未结 4 1063
鱼传尺愫
鱼传尺愫 2020-12-05 22:45

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 t

4条回答
  •  Happy的楠姐
    2020-12-05 23:10

    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

    fiddle

提交回复
热议问题