Generate list of all possible permutations of a string

后端 未结 30 2847
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  执笔经年
    2020-11-22 15:20

    Here's a non-recursive version I came up with, in javascript. It's not based on Knuth's non-recursive one above, although it has some similarities in element swapping. I've verified its correctness for input arrays of up to 8 elements.

    A quick optimization would be pre-flighting the out array and avoiding push().

    The basic idea is:

    1. Given a single source array, generate a first new set of arrays which swap the first element with each subsequent element in turn, each time leaving the other elements unperturbed. eg: given 1234, generate 1234, 2134, 3214, 4231.

    2. Use each array from the previous pass as the seed for a new pass, but instead of swapping the first element, swap the second element with each subsequent element. Also, this time, don't include the original array in the output.

    3. Repeat step 2 until done.

    Here is the code sample:

    function oxe_perm(src, depth, index)
    {
        var perm = src.slice();     // duplicates src.
        perm = perm.split("");
        perm[depth] = src[index];
        perm[index] = src[depth];
        perm = perm.join("");
        return perm;
    }
    
    function oxe_permutations(src)
    {
        out = new Array();
    
        out.push(src);
    
        for (depth = 0; depth < src.length; depth++) {
            var numInPreviousPass = out.length;
            for (var m = 0; m < numInPreviousPass; ++m) {
                for (var n = depth + 1; n < src.length; ++n) {
                    out.push(oxe_perm(out[m], depth, n));
                }
            }
        }
    
        return out;
    }
    

提交回复
热议问题