Created
November 27, 2017 18:03
-
-
Save devNoiseConsulting/d91e09ff2c693a68c31107fde7fba4e4 to your computer and use it in GitHub Desktop.
Anagram Maker - PhillyDev Slack #daily_programmer - 20171127
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
| // The permutations function is based off the answer found at | |
| // https://stackoverflow.com/a/17917159 | |
| // Converted to a more ES6 solution. | |
| // Note: permutations will return duplicates, filtering was removed as it seem | |
| // to increase the run time for larger strings. | |
| let permutations = function(string, start = '') { | |
| if (string.length == 1) { | |
| return [string]; | |
| } else { | |
| return string.split('').reduce((acc, l, i, arr) => { | |
| return acc.concat( | |
| permutations( | |
| arr | |
| .slice() | |
| .filter((v, j) => j !== i) | |
| .join(''), | |
| l | |
| ).map(v => l + v) | |
| ); | |
| }, []); | |
| } | |
| }; | |
| let anagramMaker = function(words) { | |
| let results = permutations(words[0]).filter(v => words.indexOf(v) == -1); | |
| return results[Math.floor(Math.random() * results.length)]; | |
| }; | |
| let test; | |
| let result; | |
| test = ['ab']; | |
| result = anagramMaker(test); | |
| console.log(test, result); | |
| test = ['aba', 'aab']; | |
| result = anagramMaker(test); | |
| console.log(test, result); | |
| test = ['123', '132', '231', '312', '321']; | |
| result = anagramMaker(test); | |
| console.log(test, result); | |
| test = ['hq999', '9h9q9', '9qh99']; | |
| result = anagramMaker(test); | |
| console.log(test, result); | |
| test = ['abcde123', 'ab3e1cd2', '321edbac', 'bcda1e23']; | |
| result = anagramMaker(test); | |
| console.log(test, result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment