javascript - Finding the rank of the Given string in list of all possible permutations -


i trying find rank of given string in list of possible permutations. tried come solution tries find possible permutations, assign rank them , display it.

but drastically reduces performance when length of string keeps increasing. wondering if can think of efficient solution problem..

function permute(str) {     // sort string     var arr = [];     (var = 0; < str.length; i++) arr.push(str[i]);     var sortedstring = arr.sort().join(''),         // length of string         length = str.length,         used = [];     // create boolean array length of string     while (length--) used.push(false);     // string buffer holds current string     var out = '';     // call function     dopermute(sortedstring, str, out, used, str.length, 0); } var count = 0;  function dopermute(inp, givenstring, out, used, length, level) {     // if length of string equal current level print     // permutation length eqaul string length     if (level == length) {         count++;         //console.log('perm :: ' + out + ' -- ' + count);         if (out === givenstring) {             var pp = 'rank of  :: ' + out + ' -- ' + count;             $('div').append('<p>' + pp + '</p>');         }         return;     }     (var = 0; < length; ++i) {         // if variable used continue         if (used[i]) continue;         // append current char in loop         out += inp[i];         // set variable true         used[i] = true;         // call function again         dopermute(inp, givenstring, out, used, length, level + 1);         // set false variable can reused         used[i] = false;         // remove last character of buffer         out = out.slice(0, out.length - 1)     } }  permute('dbcarf') 

fiddle

sure: if input string "cab". lowest rank string starting c get?

c note strings come before it.

abc acb bac bca 

so string starting c has minimum rank 5.this number of characters in input string come lexicographically before c.(in order a,b,c,d,e,f...)so have 2.each word starting letter can have 2 words.
next letter "a"?
minimum rank word starting "ca" can get?
5
why?
"a" best way can fill second spot remaining letters.
, same goes third element "b".
rank of "cab" 5.

in general.(assuming no duplicates, though not harder)

var w; //input string  var c[26];  var rank = 1;  (var = 0; < w.length; i++) c[w[i] - 'a']++;  (var = 0; < w.length; i++) {      //how many characters not used, come before current character      var count = 0;      (var j = 0; j < 26; j++) {          if (j == (w[i] - 'a')) break;          if (c[j] > 0) count++;      }      c[w[i] - 'a'] = 0;      rank += count * fact(w.length - - 1);  } 

Comments