2_2.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 sum of the powers of all games
  14. *
  15. * The power of a game is the smallest amount of each color of cube
  16. * that could be in bag to allow a game to be valid multiplied by each
  17. * other.
  18. */
  19. let powerSum = 0;
  20. for(const game of parsedGames) {
  21. const smallestSet = FindFewestValidCubes(game);
  22. const powerOfSet = (smallestSet.red || 1) * (smallestSet.green || 1) * (smallestSet.blue || 1)
  23. powerSum += powerOfSet;
  24. }
  25. console.log(`The sum power of the games was: ${powerSum}`);
  26. /**
  27. * Find the fewest possible cubes in the bag
  28. *
  29. * Goes through all sets in a game to find the fewest possible amount
  30. * of each colored cube for that game to be valid.
  31. *
  32. * @param {Game} parsedGame A game played
  33. */
  34. function FindFewestValidCubes (parsedGame: Game): Set {
  35. const smallestSet: Set = {
  36. red: 0,
  37. green: 0,
  38. blue: 0
  39. };
  40. for (const set of parsedGame.Sets) {
  41. if (set.red > smallestSet.red) { smallestSet.red = set.red; }
  42. if (set.green > smallestSet.green) { smallestSet.green = set.green; }
  43. if (set.blue > smallestSet.blue) { smallestSet.blue = set.blue; }
  44. }
  45. return smallestSet;
  46. }