Permutation Javascript

前端 未结 3 1971
死守一世寂寞
死守一世寂寞 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:56

    Well, 'mariush' is actually permutation 2220 if we are using your ordering scheme:

    /*jslint white: true*/
    var perm = function(s){
        'use strict';
        if(s.length === 1){
            return [s];
        }
        // For each character c in s, generate the permuations p of all
        // the other letters in s, prefixed with c.
        return [].reduce.call(s, function(p,c,i){ // permutations, char, index
            var other = s.slice(0,i) + s.slice(i+1);
            return p.concat(perm(other).map(function(oneperm){
                return c + oneperm;
            }));
        }, []);
    };
    
    alert(perm('ahimrsu').indexOf('mariush') + 1); // 2220

提交回复
热议问题