Skip to content

Instantly share code, notes, and snippets.

@JannVazTor
Created August 1, 2018 04:35
Show Gist options
  • Select an option

  • Save JannVazTor/acf603eae15d5059dc64972e56384df6 to your computer and use it in GitHub Desktop.

Select an option

Save JannVazTor/acf603eae15d5059dc64972e56384df6 to your computer and use it in GitHub Desktop.
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