Created
September 15, 2014 14:53
-
-
Save jgable/9ebc939d38fde5b2c98d to your computer and use it in GitHub Desktop.
Word Permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(''); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bugged me all weekend /cc @zpao