diff options
author | eug-vs <eugene@eug-vs.xyz> | 2023-12-09 16:42:08 +0300 |
---|---|---|
committer | eug-vs <eugene@eug-vs.xyz> | 2023-12-09 16:42:08 +0300 |
commit | c1d1ec78b95cf7656f267549c50b6c20408a9423 (patch) | |
tree | 8b805fda293b603252235782e180816c6dfaf6cf /day-7/script.ts | |
parent | 8a2061be6e795788fb5aa6b6ae93109c68af1358 (diff) | |
download | aoc-2023-c1d1ec78b95cf7656f267549c50b6c20408a9423.tar.gz |
feat(day-7): add first part solution
Diffstat (limited to 'day-7/script.ts')
-rw-r--r-- | day-7/script.ts | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/day-7/script.ts b/day-7/script.ts new file mode 100644 index 0000000..0d812f7 --- /dev/null +++ b/day-7/script.ts @@ -0,0 +1,72 @@ +import fs from "fs"; + +enum HandType { + highCard, + onePair, + twoPair, + threeOfAKind, + fullHouse, + fourOfAKind, + fiveOfAKind, +} + +const cardStrength = [ + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "T", + "J", + "Q", + "K", + "A", +]; + +function classifyHand(hand: string) { + const cards = hand.split(""); + const counts = Array.from(new Set(cards)) + .map((card) => cards.filter((c) => c === card).length) + .sort() + .reverse(); + + if (counts[0] === 5) return HandType.fiveOfAKind; + if (counts[0] === 4) return HandType.fourOfAKind; + if (counts[0] === 3 && counts[1] === 2) return HandType.fullHouse; + if (counts[0] === 3) return HandType.threeOfAKind; + if (counts[0] === 2 && counts[1] === 2) return HandType.twoPair; + if (counts[0] === 2) return HandType.onePair; + return HandType.highCard; +} + +const input = fs + .readFileSync("./input.txt") + .toString() + .split("\n") + .slice(0, -1) + .map((line) => { + const match = line.match(/(.....) (\d+)/); + if (!match) throw new Error("Unexpected format"); + return { + hand: match[1], + bid: Number(match[2]), + type: classifyHand(match[1]), + }; + }) + .sort((a, b) => { + const diff = a.type - b.type; + if (diff) return diff; + + return [0, 1, 2, 3, 4].reduce((acc, index) => { + return acc + ? acc + : cardStrength.indexOf(a.hand[index]) - + cardStrength.indexOf(b.hand[index]); + }, 0); + }) + .reduce((sum, item, index) => sum + item.bid * (index + 1), 0); + +console.log({ input }); |