From 21a4a468b0565f99be957ced224fa3483006c1f2 Mon Sep 17 00:00:00 2001 From: Seth Etter Date: Sat, 2 Dec 2023 13:39:13 -0600 Subject: [PATCH] part 1 done! --- 2023/day02/part1.ts | 46 +++++++++++++++++++++++++++++++++++++++++++-- 2023/day02/test.ts | 10 ++++++++-- 2 files changed, 52 insertions(+), 4 deletions(-) diff --git a/2023/day02/part1.ts b/2023/day02/part1.ts index 5658bc9..3b7ca0d 100644 --- a/2023/day02/part1.ts +++ b/2023/day02/part1.ts @@ -8,6 +8,48 @@ if (import.meta.main) { } export function answer(input: string): number { - console.log(input); - return 42; + const games = input.split("\n").map(parseGame); + + const bag = { r: 12, g: 13, b: 14 }; + return games + .filter((g) => isGamePossible(g, bag)) + .reduce((sum, g) => sum + g.id, 0); +} + +function isGamePossible(g: Game, bag: Round): boolean { + const colors: ColorShort[] = ["r", "g", "b"]; + return colors.every((c) => g.rounds.every((r: Round) => r[c] <= bag[c])); +} + +type Game = { id: number; rounds: Round[] }; +type Round = Record; +type ColorShort = "r" | "g" | "b"; +type Color = "red" | "green" | "blue"; + +function parseGame(l: string): Game { + const id = parseInt(l.substring(4, l.indexOf(":"))); + return { id, rounds: parseRounds(l) }; +} + +function parseRounds(l: string): Round[] { + return l + .substring(l.indexOf(": ") + 1) + .split("; ") + .map(parseRound); +} + +function parseRound(rStr: string): Round { + const countForColor = (c: Color) => + parseInt( + rStr + .trim() + .split(", ") + .find((draw) => draw.endsWith(c)) + ?.replace(` ${c}`, "") ?? "0", + ); + return { + r: countForColor("red"), + b: countForColor("blue"), + g: countForColor("green"), + }; } diff --git a/2023/day02/test.ts b/2023/day02/test.ts index ef5e047..6ed93ba 100644 --- a/2023/day02/test.ts +++ b/2023/day02/test.ts @@ -3,8 +3,14 @@ import * as p1 from "./part1.ts"; import * as p2 from "./part2.ts"; Deno.test("part1", () => { - const examples = ["abc", "def"].join("\n"); - assertEquals(p1.answer(examples), 42); + const examples = [ + "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green", + "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue", + "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red", + "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red", + "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green", + ].join("\n"); + assertEquals(p1.answer(examples), 8); }); Deno.test("part2", () => { -- 2.51.2