Skip to content

Instantly share code, notes, and snippets.

@p-a
Created December 9, 2023 20:45
Show Gist options
  • Save p-a/d3cc6661b7f9aff4766d378d82798cd8 to your computer and use it in GitHub Desktop.
Save p-a/d3cc6661b7f9aff4766d378d82798cd8 to your computer and use it in GitHub Desktop.
AoC 2023 Day 07 revisited
import { map, sort, sum } from "../../lib/arrays.js";
import { pipe } from "../../lib/utils.js";
const parse = input =>
input
.split("\n")
.map(row => row.split(" "))
.map(([hand, bid]) => [[...hand], Number(bid)]);
const RANKING_PT1 = "23456789TJQKA";
const RANKING_PT2 = "J23456789TQKA";
const cardCount = rankOrder => hand =>
hand.reduce(
(cnt, value) => (cnt[rankOrder.indexOf(value)]++, cnt),
[...rankOrder].fill(0)
);
const cardStrengths = rankOrder => hand =>
hand.map(value => rankOrder.indexOf(value).toString(16));
const rank1 = hand =>
cardCount(RANKING_PT1)(hand)
.sort((a, b) => b - a)
.concat(cardStrengths(RANKING_PT1)(hand))
.join("");
const rank2 = hand => {
const count = cardCount(RANKING_PT2)(hand);
const jokers = count.shift();
count.sort((a, b) => b - a);
count[0] += jokers;
return count
.concat(cardStrengths(RANKING_PT2)(hand))
.join("");
};
const totalWinnings = rankfn =>
pipe(
parse,
map(([hand, bid]) => [rankfn(hand), bid]),
sort(([a], [b]) => (a < b ? -1 : 1)),
map(([, bid], i) => bid * (i + 1)),
sum
);
export const part1 = totalWinnings(rank1);
export const part2 = totalWinnings(rank2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment