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:
- Remove the first letter
- Find all the permutations of the remaining letters (recursive step)
- 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".');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…