Public
Edited
Nov 7, 2023
Insert cell
Insert cell
letterScores = [...Array(26).keys()].reduce(
(scores, i) => ((scores[String.fromCharCode(97 + i)] = i + 1), scores),
{}
)
Insert cell
wordList = ["apple", "banana", "cherry", "rhecry", "date", "fig"]
Insert cell
getWordScore = (word, scores) => {
let letterArray = [...word];
let letterScores = letterArray.map((d) => scores[d]);
let sum = letterScores.reduce((previousValue, currentValue) => {
return currentValue + previousValue;
}, 0);
return sum * letterArray.length;
}
Insert cell
getWordScore("banana", letterScores)
Insert cell
wordList.map((d) => getWordScore(d, letterScores))
Insert cell
["apple", "banana", "cherry", "date", "fig", "eid", "ace"].map((d) =>
getWordScore(d, letterScores)
)
Insert cell
scoreWordGame = (list, scores) => {
let arrayWithScore = list
.map((d) => {
let myObject = {};
myObject.score = getWordScore(d, scores);
myObject.word = d;
return myObject;
})
.sort((a, b) => b.score - a.score);

if (arrayWithScore[0].score > arrayWithScore[1].score) {
return arrayWithScore[0].word;
} else {
let word1 = arrayWithScore[0].word[0];
let word2 = arrayWithScore[1].word[0];

if (scores[word1] < scores[word2]) {
return arrayWithScore[0].word;
} else {
return arrayWithScore[1].word;
}
}
return arrayWithScore;
}
Insert cell
scoreWordGame(wordList, letterScores)
Insert cell
scoreWordGame(wordList, letterScores) === "cherry"
Insert cell
scoreWordGame_v2 = (list, scores) => {
let arrayWithScore = list
.map((d) => ({
score: getWordScore(d, scores),
word: d
}))
.sort((a, b) => {
if (b.score === a.score) {
return a.word.localeCompare(b.word); // for lexicographic comparison
}
return b.score - a.score;
});

// Now we have a sorted array, but we need to find all with the highest score
let maxScore = arrayWithScore[0].score;
let highestScoringWords = arrayWithScore.filter(
(item) => item.score === maxScore
);

// If there's only one word with the highest score, return it
if (highestScoringWords.length === 1) {
return highestScoringWords[0].word;
}

// If there's more than one, sort them lexicographically and return the first one
highestScoringWords.sort((a, b) => a.word.localeCompare(b.word));
return highestScoringWords[0].word;
}
Insert cell
scoreWordGame_v2(wordList, letterScores)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more