Created
August 1, 2018 04:35
-
-
Save JannVazTor/acf603eae15d5059dc64972e56384df6 to your computer and use it in GitHub Desktop.
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
| function wordLadder(beginWord, endWord, wordList) { | |
| debugger; | |
| var availableLetters = getUniqueLettersFromDictionary(wordList); | |
| var wordFound = []; | |
| var wordChanges = 0; | |
| for (var i = 0; i < beginWord.length; i += 1) { | |
| var currArrayWord = beginWord.split(''); | |
| for (var j = 0; j < availableLetters.length; j += 1) { | |
| currArrayWord[i] = availableLetters[j]; | |
| var newWord = currArrayWord.join(''); | |
| if (newWord === beginWord) continue; | |
| var index = wordList.indexOf(newWord); | |
| if (index !== -1) { | |
| wordChanges++; | |
| wordFound.push(wordList.splice(index, 1)); | |
| } | |
| if (newWord === endWord) { | |
| break; | |
| } | |
| } | |
| } | |
| return wordChanges; | |
| } | |
| function getUniqueLettersFromDictionary(dictionary) { | |
| return eraseDuplicatedLetters(dictionary.toString()).replace(',', ''); | |
| } | |
| function eraseDuplicatedLetters(word) { | |
| var result = ''; | |
| for (var i = 0; i < word.length; i += 1) { | |
| if (result.indexOf(word[i]) < 0) result += word[i]; | |
| } | |
| return result; | |
| } | |
| document.write(wordLadder('hit', 'cog', ['hot', 'dot', 'lot', 'log', 'cog'])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment