2_1.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { LoadInput } from "../common.ts";
  2. import { ParseGameStrings, type Game, type Set } from "./2_common.ts";
  3. const test = [
  4. "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green",
  5. "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue",
  6. "Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red",
  7. "Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red",
  8. "Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green",
  9. ];
  10. const input = await LoadInput(2);
  11. const parsedGames = ParseGameStrings(input);
  12. /**
  13. * The target amount of each colored cube in a games bag
  14. *
  15. * As reported by the elf, only games with the maximum amount of each
  16. * color of cube specified here are valid
  17. */
  18. const maxCubes: Set = {
  19. red: 12,
  20. green: 13,
  21. blue: 14,
  22. };
  23. let sumOfValidIDs = 0;
  24. for (const game of parsedGames) {
  25. if (ValidateGames(game, maxCubes)) {
  26. sumOfValidIDs += game.ID;
  27. }
  28. }
  29. console.log(`The sum of valid game ID's is: ${sumOfValidIDs}`);
  30. /**
  31. * Validate whether a game was possible
  32. *
  33. * A game is only valid if none of the sets in the game played
  34. * contained more of than the target maximum for that color.
  35. *
  36. * @param {Game} gameToValidate A game to validate
  37. * @param {Set} targetMaximum The maximum of each color in a set required for a game to be valid
  38. */
  39. function ValidateGames(gameToValidate: Game, targetMaximum: Set): boolean {
  40. for(const set of gameToValidate.Sets) {
  41. if (set.red > targetMaximum.red
  42. || set.green > targetMaximum.green
  43. || set.blue > targetMaximum.blue) { return false; }
  44. }
  45. return true;
  46. }