String permutation
JavaScript
function permute(str) {
console.log('permuting...', str);
var permutations = [];
if (typeof str !== "string") {
return null;
}
//simpliest case "" -> []
if (str.length === 0) {
permutations.push("");
return permutations;
}
//simple case "a" -> ['a']
else if (str.length === 1) {
permutations.push(str);
return permutations;
}
//recursive case "abc" -> "a" inserted in all permutations of "b" and "c"
else {
var head = str.charAt(0);
var tail = str.substring(1, str.length);
//array with results
var permutatedTail = permute(tail);
console.log("head", head);
console.log("permutatedTail:", permutatedTail);
//insert head into every posible combination of combinationList
permutatedTail.forEach(function (chunk) {
console.log("chunk: ", chunk);
for (var i = 0; i <= chunk.length; i++) {
var insertd = chunk.insertInto(i, head);
permutations.push(insertd);
}
});
console.log('returning:', permutations);
return permutations;
}
}
String.prototype.insertInto = function (position, s) {
return this.slice(0, position) + s + this.slice(position);
};
var res = permute("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");
var resultsContainer = document.createElement('ul');
res.forEach(function(r){
var listEl = document.createElement('li');
var content = document.createTextNode(r);
listEl.appendChild(content);
resultsContainer.appendChild(listEl);
});
document.body.appendChild(resultsContainer);