Last active
March 1, 2024 06:20
-
-
Save jericrealubit/ff9402c1a049fb67dc62383d22a92157 to your computer and use it in GitHub Desktop.
count the word that have at least 1 same letter from other word in the sentence
This file contains 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
// count the word that have at least 1 same letter from other word in the sentence, | |
// will check letters only special characters will be ignored | |
function countSameLetterInWord(sentence) { | |
// remove special characters from the input | |
let input = sentence.replace(/[^a-zA-Z ]/g, ""); | |
//console.log(input); | |
let words = input.split(" "); | |
let tempWords; | |
let tempLetter; | |
let found; | |
let i = 0; | |
let result = []; | |
words.forEach((word) => { | |
tempWords = words.filter(val => val !== word); | |
//console.log(tempWords); | |
tempWords.forEach((tempWord) => { | |
i = word.length; | |
//console.log(i+" "+tempWord); | |
while (i > 0) { | |
i--; | |
tempLetter = word.charAt(i); | |
//console.log(tempLetter); | |
found = isLetterInWord(tempLetter, tempWord); | |
//console.log(found); | |
if (found) { | |
result.push(tempWord); | |
} | |
} | |
}); | |
}); | |
return countUnique(result); | |
} | |
let input = "apple banana?? c??cc nnnnY zzzzz! !yyyy"; // 4 | |
console.log("result: "+ countSameLetterInWord(input)); | |
function isLetterInWord(letter, word) { | |
return word.includes(letter); | |
} | |
function countUnique(iterable) { | |
return new Set(iterable).size; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment