Skip to content

Instantly share code, notes, and snippets.

@lffg
Last active January 4, 2022 02:37
Show Gist options
  • Save lffg/b827dac3b083629b7b7ba7e90f2653e4 to your computer and use it in GitHub Desktop.
Save lffg/b827dac3b083629b7b7ba7e90f2653e4 to your computer and use it in GitHub Desktop.
// Write a script that creates an array with 10000 random words between 3 and 5
// characters, and returns the number of words that are palindromes in that
// array. Notes: The code needs to be in javascript You’ll need to return just
// the number of words.
console.log(main());
function main() {
return Array.from({ length: 10_000 })
.map(RandomAlphabeticString(3, 5))
.filter(isPalindrome).length;
}
function RandomAlphabeticString(min, max) {
const a = 'a'.charCodeAt(0);
const z = 'z'.charCodeAt(0);
return () => {
return Array.from({ length: random(min, max) })
.map(() => String.fromCharCode(random(a, z)))
.join('');
};
}
function random(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function isPalindrome(string) {
for (let i = 0; i < Math.floor(string.length / 2); i++) {
if (string.at(i) !== string.at(-(i + 1))) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment