Public
Edited
Dec 8, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
lines = input
.split("\n")
.map((line) => line.split(" "))
.map(([hand, bid]) => [hand, parseInt(bid)])
Insert cell
Insert cell
getFrequencyTable = (cards) =>
_.sortBy(_.entries(_.countBy(cards)), ([_, count]) => -count)
Insert cell
getHand = (freq) => {
switch (freq.length) {
case 5:
return 0; // High card
case 4:
return 1; // One pair
case 3:
if (freq[0][1] === 2) return 2; // Two pair
return 3; // Three of a kind
case 2:
if (freq[0][1] === 3) return 4; // Full house
return 5; // Four of a kind
case 1: // Five of a kind
return 6;
}
}
Insert cell
getCardScore = Object.fromEntries(
Array.from("AKQJT98765432")
.reverse()
.map((c, i) => [c, i])
)
Insert cell
sortedCards = _.sortBy(lines, ([hand, _bid]) =>
String.fromCharCode(
getHand(getFrequencyTable(hand)),
...Array.from(hand).map((x) => getCardScore[x])
)
)
Insert cell
part1 = _.sum(sortedCards.map(([_, bid], i) => bid * (i + 1)))
Insert cell
Insert cell
Insert cell
getCardScore_ = Object.fromEntries(
Array.from("AKQT98765432J")
.reverse()
.map((c, i) => [c, i])
)
Insert cell
sortedCardsWithJoker = _.sortBy(lines, ([hand, _bid]) => {
const [jokers, rest] = _.partition(hand, (x) => x === "J");
const jokersCount = jokers.length;
let freq = getFrequencyTable(rest);
if (freq.length) {
freq[0][1] += jokersCount;
} else {
freq = [["J", 5]];
}
return String.fromCharCode(
getHand(freq),
...Array.from(hand).map((x) => getCardScore_[x])
);
})
Insert cell
part2 = _.sum(sortedCardsWithJoker.map(([_, bid], i) => bid * (i + 1)))
Insert cell
Insert cell
Insert cell
input = textarea || select.value
Insert cell
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