Permutation Javascript

前端 未结 3 1981
死守一世寂寞
死守一世寂寞 2020-12-21 14:01

So I have this code now, and in input I have in ascending order my name\'s letters \"ahimrsu\". I need to show up the right number for \"mariush\" from all combinations whic

3条回答
  •  我在风中等你
    2020-12-21 14:58

    Algorithm for string permutation will be a little bit more complicated with recursive step (it's possible to code it without recursion though).

    The next javascript implementation is based on the description of the algorithm from this answer:

    1. Remove the first letter
    2. Find all the permutations of the remaining letters (recursive step)
    3. Reinsert the letter that was removed in every possible location.

    Implementation then something like this:

    function permutation(str) {
    
        if (str.length == 1) {
            return [str];
        }
    
        var first = str[0],  // Step #1
            perms = permutation(str.slice(1)), // Step #2
            result = [];
    
        // Step #3
        for (var i = 0; i < perms.length; i++) {
            for (var j = 0; j <= perms[i].length; j++) {
                result.push( perms[i].slice(0, j) + first + perms[i].slice(j) );
            }
        }
    
        return result;
    }
    
    console.log(permutation('ahimrsu'));
    

    Above implementation gives 5040 combinations, which seems to be correct, since 7! == 5040 (number of permutations is a factorial of the number of chars).

    Now when you have all possible permutations array you can easily find specific string occurrence:

    var combinations = permutation('ahimrsu'); 
    var index = combinations.indexOf('mariush'); // Index of the "mariush"
    alert('"mariush" is the ' + (index + 1) + 'th permutation of "ahimrsu".');
    

提交回复
热议问题