Published
Edited
Feb 22, 2022
1 star
Insert cell
Insert cell
{
let occurrences = getOccurrences();

function empty() {
for (let i = 0; i < 26; i++) {
for (let j = 0; j < 5; j++) {
if (occurrences[String.fromCharCode("a".charCodeAt(0) + i)][j] != 0) {
return false;
}
}
}
return true;
}

const foundWords = [];
const foundLetters = [{}, {}, {}, {}, {}];
while (!empty()) {
// Find most lucrative word
let maxScore = null;
let maxWord = null;
for (const word of sortByOccurrences(words, occurrences)) {
if (foundWords.includes(word)) continue;
let score = 0;
for (let i = 0; i < 5; i++) {
// Penalize found letters
if (foundLetters[i][word.charAt(i)]) {
score--;
}
}
if (maxScore == null || score > maxScore) {
maxScore = score;
maxWord = word;
}
}

foundWords.push(maxWord);
for (let i = 0; i < 5; i++) {
foundLetters[i][maxWord.charAt(i)] = true;
}

// Recalculate occurrences
occurrences = getOccurrences(foundWords, foundLetters);
}
return foundWords;
}
Insert cell
function sortByOccurrences(words, occurrences) {
words = words.slice(); // don't alter base list
const score = (word) => {
let total = 0;
for (let i = 0; i < 5; i++) {
total += occurrences[word.charAt(i)][i];
}
return total;
};
words = words.sort((a, b) => score(a) - score(b));
return words;
}
Insert cell
getOccurrences()
Insert cell
function getOccurrences(
excludeWords = [],
exhaustedLetters = [{}, {}, {}, {}, {}]
) {
const occurrences = {};
for (let i = 0; i < 26; i++) {
occurrences[String.fromCharCode("a".charCodeAt(0) + i)] = [0, 0, 0, 0, 0];
}
for (const word of words) {
let allFound = true;
for (let i = 0; i < 5; i++) {
if (exhaustedLetters[i][word.charAt(i)] == null) {
allFound = false;
break;
}
}
if (allFound) continue;
for (let i = 0; i < 5; i++) {
occurrences[word.charAt(i)][i]++;
}
}
return occurrences;
}
Insert cell
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