advent-of-code-2023/src/day_two.alternative.ts

54 lines
1.9 KiB
TypeScript

import { Cubes } from "./day_two";
export class Game {
constructor(
public readonly id: number,
private readonly rounds: Cubes[]
) {}
public static parse(input: string): Game {
const [gameId, roundsInput] = input.split(':');
const id = parseInt(gameId.split(' ')[1], 10);
const rounds = roundsInput.split(';').map(round => {
return round.trim().split(',').map(cube => cube.trim()).reduce((total, cube) => {
const [amount, color] = cube.split(' ');
total[color as keyof Cubes] = parseInt(amount, 10);
return total;
}, {blue: 0, green: 0, red: 0} as Cubes);
});
return new Game(id, rounds);
}
private minimumCubesRequired(): Cubes {
return this.rounds.reduce((total, round) => {
Object.keys(round).forEach(color => {
total[color as keyof Cubes] = Math.max(total[color as keyof Cubes], round[color as keyof Cubes]);
});
return total;
}, {blue: 0, green: 0, red: 0} as Cubes);
}
public calculateMinimumCubePowers(): number {
const minimumCubes = this.minimumCubesRequired();
return minimumCubes.blue * minimumCubes.green * minimumCubes.red;
}
public isPossible(limits: Cubes): boolean {
return this.rounds.every(round => {
return Object.keys(round).every(color => {
return round[color as keyof Cubes] <= limits[color as keyof Cubes];
});
});
}
}
export const calculatePossibleGames = (games: Game[], limits: Cubes): number => {
const possibleGames = games.filter(game => game.isPossible(limits));
return possibleGames.reduce((total, game) => total + game.id, 0);
}
export const calculateMinimumCubePowers = (games: Game[]): number => {
return games.reduce((total, game) => total + game.calculateMinimumCubePowers(), 0);
}