diff --git a/src/2023/day02/solution.ts b/src/2023/day02/solution.ts index db064a1..d291040 100644 --- a/src/2023/day02/solution.ts +++ b/src/2023/day02/solution.ts @@ -20,3 +20,28 @@ export function part1(input: string): number { // [ true, true, false, false, true ] return validGames.reduce((acc, val, i) => (val ? acc + (i + 1) : acc), 0); } + +export function part2(input: string): number { + const games = input.split('\n'); + + const validGames = games.map((game, i) => { + const maxCubes = {red: 0, green: 0, blue: 0}; + const subsets = game.split(': ')[1].split('; '); + + subsets.forEach(subset => { + const sets = subset.split(', '); + return sets.map(set => { + const [amount, color] = set.split(' '); + const currentMax = maxCubes[color as keyof typeof maxCubes]; + if (Number(amount) > currentMax) { + maxCubes[color as keyof typeof maxCubes] = Number(amount); + } + }); + }); + + return maxCubes.red * maxCubes.green * maxCubes.blue; + }); + + const result = validGames.reduce((acc, val) => acc + val, 0); + return result; +} diff --git a/src/2023/day02/test.spec.ts b/src/2023/day02/test.spec.ts index 6295656..009bc80 100644 --- a/src/2023/day02/test.spec.ts +++ b/src/2023/day02/test.spec.ts @@ -1,6 +1,6 @@ import example from './example.txt'; import input from './input.txt'; -import {part1} from './solution'; +import {part1, part2} from './solution'; describe('Advent of Code 2023 - Day 2', () => { describe('part 1', () => { @@ -11,4 +11,13 @@ describe('Advent of Code 2023 - Day 2', () => { expect(part1(input)).toBe(2685); }); }); + + describe('part 2', () => { + test('test round', () => { + expect(part2(example)).toBe(2286); + }); + test('solution', () => { + expect(part2(input)).toBe(83707); + }); + }); });