Skip to content

Instantly share code, notes, and snippets.

@jtribble
Last active March 19, 2016 21:59
Show Gist options
  • Save jtribble/797dc9cf8cf8b0d42d10 to your computer and use it in GitHub Desktop.
Save jtribble/797dc9cf8cf8b0d42d10 to your computer and use it in GitHub Desktop.
Find all permutations of a string using base case & build approach. See: https://en.wikipedia.org/wiki/Permutation
//
// Find all permutations of a string using base case & build approach
//
// See: https://en.wikipedia.org/wiki/Permutation
//
'use strict';
if (!String.prototype.splice) {
/**
* @method - Add "splice" to String
*/
String.prototype.splice = function(start, deleteCount, insert) {
if (start > this.length) {
start = this.length;
}
if (!insert) {
insert = '';
}
return this.slice(0, start) + insert + this.slice(start + deleteCount);
};
}
/**
* Find all permutations of a string
*
* @param {string} input - The string input
* @return {array} - The list of permutations
*/
const permutations = function(input) {
// if input is not a string, throw error
if (typeof input !== 'string') {
throw new Error('Input was invalid');
}
// use base case & build approach
let perms = [''];
for (let i = 0; i < input.length; i++) {
let char = input.charAt(i);
let permsLen = perms.length;
// loop through each existing permuation
for (let j = 0; j < permsLen; j++) {
// add the input[i] character at each point in the string
for (let k = 0; k <= perms[j].length; k++) {
perms.push(perms[j].splice(k, 0, char));
}
}
}
// we're only interested in permutations of the full string length
// also, sort the list, since we don't really care about performance here
return perms.filter(perm => perm.length === input.length).sort();
};
//
// For usage with Node.js
//
if (typeof window === 'undefined' && typeof global === 'object') {
// if no args provided, print usage
if (process.argv.length < 3) {
return console.log('Usage: node permutations.js {string}');
}
// get string from args
const str = process.argv[2];
// return all permutations
return console.log(permutations(str));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment