Last active
March 30, 2020 22:02
-
-
Save ok1a/0585fedc10d2156a02e08b9b97bf0952 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 findMinDistance(sentence, word1, word2) { | |
const sentenceArr = sentence.split(' '); | |
const wordDict = {}; | |
wordDict[word1] = word2; | |
wordDict[word2] = word1; | |
let distanceArr = []; | |
let distanceCounter = 0; | |
let lastFoundKeyword = ''; | |
for (let i = 0; i < sentenceArr.length; i++) { | |
let currentWord = sentenceArr[i]; | |
if (lastFoundKeyword) { | |
distanceCounter++; | |
} | |
if (currentWord === word1 || currentWord === word2) { | |
if (currentWord === lastFoundKeyword) { | |
distanceCounter = 0; | |
} | |
if (lastFoundKeyword && wordDict[lastFoundKeyword] === currentWord) { | |
distanceArr.push(distanceCounter); | |
distanceCounter = 0; | |
} | |
lastFoundKeyword = currentWord; | |
} | |
} | |
const sortedDistanceArr = distanceArr.sort(); | |
const minDistance = sortedDistanceArr[0]; | |
return minDistance; | |
} | |
const sentencesToTest = [ | |
'the quick brown quick fox brown the jumped over the dog lazy quick the brown dog lazy fox', | |
'the quick brown the', | |
'apple banana orange grape lemon watermelon tomato potato corn apple', // I forgot I made apple the last word and I spent 20 minutes trying to debug why this test was returning 4 instead of 5 when it should have been 4 all along. RIP. | |
'a b c b a c a b a ', | |
'arkansas alabama georgia california california alaska california arizona arkansas california alabama california colorado wyoming arizona virginia deleware georgia connecticut arizona california colorado virginia arkansas', | |
'd a b b b d b l b b b a b b d b l a', | |
]; | |
const wordPairsToTest = [ | |
['fox', 'lazy'], | |
['the', 'brown'], | |
['apple', 'watermelon'], | |
['a', 'c'], | |
['california', 'arkansas'], | |
['d', 'a'], | |
]; | |
const testIndex = 5; | |
console.log( | |
findMinDistance( | |
sentencesToTest[testIndex], | |
wordPairsToTest[testIndex][0], | |
wordPairsToTest[testIndex][1], | |
), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment