logo

adventofcode

Code used to solve https://adventofcode.com/, one branch per year git clone https://hacktivis.me/git/adventofcode.git

day2_part2.ha (1840B)


  1. // SPDX-FileCopyrightText: 2023 Haelwenn (lanodan) Monnier <contact+aoc2023@hacktivis.me>
  2. // SPDX-License-Identifier: MIT
  3. use bufio;
  4. use strings;
  5. use strconv;
  6. use fmt;
  7. use os;
  8. use io;
  9. type game = struct {
  10. red: uint,
  11. green: uint,
  12. blue: uint,
  13. };
  14. export fn main() void = {
  15. let total = 0u32;
  16. for(let id = 1u32; true; id += 1) {
  17. const line = match(bufio::read_line(os::stdin)) {
  18. case let l: []u8 => yield l;
  19. case io::EOF => break;
  20. case => abort();
  21. };
  22. const line = strings::fromutf8(line)!;
  23. let val = game {
  24. red = 0,
  25. green = 0,
  26. blue = 0,
  27. };
  28. const (id_str, reveal) = strings::cut(line, ": ");
  29. //fmt::printfln("{}={} | {}", id, id_str, reveal)!;
  30. let hands = strings::tokenize(reveal, "; ");
  31. for(true) {
  32. const hand = match(strings::next_token(&hands)) {
  33. case let h: str => yield h;
  34. case void => break;
  35. };
  36. //fmt::printfln(" hand: {}", hand)!;
  37. let colors = strings::tokenize(hand, ", ");
  38. for(true) {
  39. const color = match(strings::next_token(&colors)) {
  40. case let h: str => yield h;
  41. case void => break;
  42. };
  43. //fmt::printfln(" color: {}", color)!;
  44. const (n, color) = strings::cut(color, " ");
  45. const n = match(strconv::stou(n)) {
  46. case let u: uint =>
  47. yield u;
  48. case =>
  49. fmt::fatalf("Not a number: {}", n);
  50. };
  51. switch(color) {
  52. case "red" =>
  53. if(n > val.red) {
  54. val.red = n;
  55. };
  56. case "green" =>
  57. if(n > val.green) {
  58. val.green = n;
  59. };
  60. case "blue" =>
  61. if(n > val.blue) {
  62. val.blue = n;
  63. };
  64. case =>
  65. fmt::fatalf("Unknown color: {}", color);
  66. };
  67. };
  68. };
  69. fmt::printf("{} = R{}, G{}, B{}", id, val.red, val.green, val.blue)!;
  70. const pow = val.red * val.green * val.blue;
  71. fmt::printfln(" POW: {}", pow)!;
  72. total += pow;
  73. };
  74. fmt::printfln("Total: {}", total)!;
  75. };