Skip to content

Instantly share code, notes, and snippets.

@DiegoVictor
Last active July 13, 2021 15:41
Show Gist options
  • Save DiegoVictor/ee46189f45a3895bb04b49c4b7106e57 to your computer and use it in GitHub Desktop.
Save DiegoVictor/ee46189f45a3895bb04b49c4b7106e57 to your computer and use it in GitHub Desktop.
Palindrome Challenge
// 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