Skip to content

Instantly share code, notes, and snippets.

@jgable
Created September 15, 2014 14:53
Show Gist options
  • Save jgable/9ebc939d38fde5b2c98d to your computer and use it in GitHub Desktop.
Save jgable/9ebc939d38fde5b2c98d to your computer and use it in GitHub Desktop.
Word Permutations
// To run with node: npm install lodash && node perms.js star
var _ = require('lodash'),
words = ['stars'];
function getPermutations(word) {
// Stop case for single character
if (word.length === 1) {
return [word];
}
// For each letter...
return _.reduce(word, function (result, letter, idx) {
// Grab the other letters
var rest = [word.slice(0, idx), word.slice(idx + 1)].join(''),
// Get all permutations of the other letters to the right
rightCombos = getPermutations(rest);
// For each right combo, add the current letter onto it and
// push into result
_.each(rightCombos, function (combo) {
result.push(letter + combo);
});
// Return the aggregated results from all letter combinations
return result;
}, []);
}
// Allow passing in words to do
if (process.argv.length > 2) {
words = process.argv.slice(2);
}
_.each(words, function (word) {
var perms = _.unique(getPermutations(word)),
title = word + ' (' + perms.length + ')';
console.log(title);
console.log(new Array(title.length + 1).join('='));
_.each(perms, function (perm) {
console.log(perm);
});
console.log('');
});
@jgable
Copy link
Author

jgable commented Sep 15, 2014

Bugged me all weekend /cc @zpao

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment