logo

adventofcode

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

day1_part2.ha (2434B)


  1. // SPDX-FileCopyrightText: 2023 Haelwenn (lanodan) Monnier <contact+aoc2023@hacktivis.me>
  2. // SPDX-License-Identifier: MIT
  3. // This is broken code, the hare regex library is currently (2023-12-02) incomplete
  4. // I solved day1_part2 with day1_part2.pl instead
  5. use bufio;
  6. use strings;
  7. use fmt;
  8. use os;
  9. use io;
  10. use regex;
  11. use strconv;
  12. fn stoi(line: str) int = {
  13. const line = strings::multireplace(line,
  14. ("one", "1"),
  15. ("two", "2"),
  16. ("three", "3"),
  17. ("four", "4"),
  18. ("five", "5"),
  19. ("six", "6"),
  20. ("seven", "7"),
  21. ("eight", "8"),
  22. ("nine", "9"),
  23. );
  24. return strconv::stoi(line)!;
  25. };
  26. export fn main() void = {
  27. let total = 0u32;
  28. const fre = regex::compile(`^([0-9]|one|two|three|four|five|six|seven|six|seven|eight|nine)`)!;
  29. const lre = regex::compile( `([0-9]|one|two|three|four|five|six|seven|six|seven|eight|nine)$`)!;
  30. defer regex::finish(&fre);
  31. defer regex::finish(&lre);
  32. fmt::printfln("Regexes compiled")!;
  33. for(true) {
  34. const line = match(bufio::read_line(os::stdin)) {
  35. case let l: []u8 => yield l;
  36. case io::EOF => break;
  37. case => abort();
  38. };
  39. let line = strings::fromutf8(line)!;
  40. fmt::printf("{} ", line)!;
  41. // Try1: Invalid, need to only replace first spelled number and last one, not all
  42. //const line = strings::multireplace(line,
  43. // ("one", "1"),
  44. // ("two", "2"),
  45. // ("three", "3"),
  46. // ("four", "4"),
  47. // ("five", "5"),
  48. // ("six", "6"),
  49. // ("seven", "7"),
  50. // ("eight", "8"),
  51. // ("nine", "9"),
  52. //);
  53. // Try2: Definitely invalid "eightwothree" needs to be 8wo3
  54. //line = strings::replace(line, "one", "1");
  55. //line = strings::replace(line, "two", "2");
  56. //line = strings::replace(line, "three", "3");
  57. //line = strings::replace(line, "four", "4");
  58. //line = strings::replace(line, "five", "5");
  59. //line = strings::replace(line, "six", "6");
  60. //line = strings::replace(line, "seven", "7");
  61. //line = strings::replace(line, "eight", "8");
  62. //line = strings::replace(line, "nine", "9");
  63. //fmt::printf("→ {} ", line)!;
  64. let fre_r = regex::find(&fre, line);
  65. let lre_r = regex::find(&lre, line);
  66. defer regex::result_free(fre_r);
  67. defer regex::result_free(lre_r);
  68. fmt::printfln("Results!")!;
  69. assert(len(fre_r) > 0);
  70. assert(len(lre_r) > 0);
  71. const first = stoi(fre_r[0].content);
  72. const last = stoi(lre_r[0].content);
  73. const val = (first*10)+last;
  74. fmt::printfln("= {}", val)!;
  75. total += val: u32;
  76. };
  77. fmt::printfln("Total: {}", total)!;
  78. };