diff options
author | eug-vs <eugene@eug-vs.xyz> | 2023-12-02 17:20:16 +0300 |
---|---|---|
committer | eug-vs <eugene@eug-vs.xyz> | 2023-12-02 17:20:16 +0300 |
commit | 5406a3a52036b95726f368d0b22f8c73da48f9a0 (patch) | |
tree | d470824ed21069a307bb0b02ed596ba1bcbc3562 /day-2/script.ts | |
parent | dd4171f8253aeefaebc97126543f664cbdafcdc8 (diff) | |
download | aoc-2023-5406a3a52036b95726f368d0b22f8c73da48f9a0.tar.gz |
feat(day-2): add part 1 solution
Diffstat (limited to 'day-2/script.ts')
-rw-r--r-- | day-2/script.ts | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/day-2/script.ts b/day-2/script.ts new file mode 100644 index 0000000..4e29bbb --- /dev/null +++ b/day-2/script.ts @@ -0,0 +1,52 @@ +import fs from "fs"; + +const input = fs.readFileSync("./input.txt").toString(); + +const COLORS = ["red", "green", "blue"] as const; +type Color = (typeof COLORS)[number]; + +type Draw = Record<Color, number>; + +interface Game { + id: number; + draws: Draw[]; +} + +function isPossible( + game: Game, + maxDraw: Draw = { red: 12, green: 13, blue: 14 }, +) { + return game.draws.reduce((acc, draw) => { + return ( + acc && + COLORS.every((color) => { + return draw[color] <= maxDraw[color]; + }) + ); + }, true); +} + +const result = input + .split("\n") + .slice(0, -1) + .map((line) => { + const [gameStr, drawsStr] = line.split(": "); + const id = Number(gameStr.slice("Game ".length)); + + const draws = drawsStr.split("; ").map((record) => { + const draws = record.split(", ").reduce( + (acc, draw) => { + const [number, color] = draw.split(" "); + acc[color] = Number(number); + return acc; + }, + { red: 0, green: 0, blue: 0 }, + ); + return draws; + }); + return { id, draws }; + }) + .filter((game) => isPossible(game)) + .reduce((acc, game) => acc + game.id, 0); + +console.log({ result }); |