Created
November 6, 2023 10:40
-
-
Save JoshuaRotimi/13707646afe3dcd8aa19c4f38edeb24b to your computer and use it in GitHub Desktop.
Given a list of words and a dictionary of letter scores, find the word with the highest score according to the rules.
This file contains hidden or 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
| /* | |
| Given a list of words and a dictionary of letter scores, find the word with the highest score | |
| according to the rules: score = word_length * (sum of letter scores in the word). | |
| If there are multiple words with the same highest score, | |
| return the lexicographically smallest one. | |
| */ | |
| const wordList = ["apple", "banana", "cherry", "date", "fig"]; | |
| const letterScores = [...Array(26).keys()].reduce( | |
| (scores, i) => ((scores[String.fromCharCode(97 + i)] = i + 1), scores), | |
| {} | |
| ); | |
| function scoreWordGame(words, letterObj) { | |
| // Sort the array lexicographically | |
| words.sort(function (a, b) { | |
| return a.localeCompare(b); | |
| }); | |
| let wordNumbers = []; | |
| for (let i = 0; i < words.length; i++) { | |
| let total = 0; | |
| for (const letter of words[i]) { | |
| total += letterObj[letter]; | |
| } | |
| wordNumbers.push(total); | |
| total = 0; | |
| } | |
| const maxNum = Math.max(...wordNumbers); | |
| const largest = wordNumbers.indexOf(maxNum); | |
| return words[largest]; | |
| } | |
| const example = scoreWordGame(wordList, letterScores); | |
| console.log(example); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment