Initial Commit

This commit is contained in:
2024-11-27 10:10:41 +01:00
commit 3cb015b230
22 changed files with 519 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="2023-02" type="BunRunConfiguration">
<option name="program" value="2023/02/run.ts" />
<option name="workingDirectory" value="$PROJECT_DIR$" />
<method v="2" />
</configuration>
</component>
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'bun:test';
import { solveFirst, solveSecond } from './index.ts';
describe('2023-02', () => {
const testInput = `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`;
it('first', () => {
expect(solveFirst(testInput, { red: 12, green: 13, blue: 14 })).toBe(8);
});
it('second', () => {
expect(solveSecond(testInput)).toBe(2286);
});
});
+45
View File
@@ -0,0 +1,45 @@
import { groupBy, multBy, sumArray, sumBy } from '../../utils/array.ts';
export type AllowedCubes = Record<string, number>;
function parseInput(input: string) {
const matchLine = input.matchAll(/^Game (\d*): (.*)$/gm);
return Array.from(matchLine, (m) => ({
id: Number(m[1]),
rounds: m[2].split('; ').map((r) =>
r.split(', ').map((g) => {
const [amount, color] = g.split(' ');
return { color, amount: Number(amount) };
})
)
}));
}
export function solveFirst(input: string, allowed: AllowedCubes): number {
const games = parseInput(input);
const possible = games.filter(
(g) =>
!g.rounds.some((r) =>
r.some((s) => !(s.color in allowed) || s.amount > allowed[s.color])
)
);
return sumBy(possible, (a) => a.id);
}
export function solveSecond(input: string): number {
const games = parseInput(input);
const leastCubes = games.map((g) =>
groupBy(g.rounds.flat(), (e) => e.color).map(({ key, elements }) => ({
key,
amount: elements.toSorted((a, b) => b.amount - a.amount)[0].amount
}))
);
const powers = leastCubes.map((cubes) => multBy(cubes, (c) => c.amount));
return sumArray(powers);
}
+12
View File
@@ -0,0 +1,12 @@
import { join } from 'path';
import { solveFirst, solveSecond } from './index.ts';
const input = await Bun.file(join(__dirname, 'input.txt')).text();
const firstAnswer = solveFirst(input, { red: 12, green: 13, blue: 14 });
console.log(firstAnswer);
const secondAnswer = solveSecond(input);
console.log(secondAnswer);