-
-
Save p-a/d3cc6661b7f9aff4766d378d82798cd8 to your computer and use it in GitHub Desktop.
AoC 2023 Day 07 revisited
This file contains 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
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