Last active
July 13, 2021 15:41
-
-
Save DiegoVictor/ee46189f45a3895bb04b49c4b7106e57 to your computer and use it in GitHub Desktop.
Palindrome Challenge
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
// node . [total-words] (e.g. node . 1000) | |
const firstAlphabetLetter = "a".charCodeAt(); | |
const alphabetRange = "z".charCodeAt() - firstAlphabetLetter; | |
const [,,totalWordsArg = 10000] = process.argv; | |
const generateRandomWord = (min, max) => { | |
const randomMaxChars = Math.floor(Math.random() * max); | |
let word = ""; | |
for (let i = 0; i <= min || i <= randomMaxChars; i++) { | |
word += String.fromCharCode( | |
firstAlphabetLetter + Math.random() * alphabetRange | |
); | |
} | |
return word; | |
}; | |
const main = (totalWords = 10000) => { | |
const words = []; | |
for (let i = 0; i <= totalWords; i++) { | |
words.push(generateRandomWord(3, 5)); | |
} | |
return words.reduce((sum, word) => { | |
if (word === word.split("").reverse().join("")) { | |
sum++; | |
} | |
return sum; | |
}, 0); | |
}; | |
const palindromeCount = main(totalWordsArg); | |
console.log(`Found ${palindromeCount} palindrome words`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment