Skip to content

Instantly share code, notes, and snippets.

@jericrealubit
Last active March 1, 2024 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jericrealubit/ff9402c1a049fb67dc62383d22a92157 to your computer and use it in GitHub Desktop.
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
// 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