logo

adventofcode

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

day3.0.ha (1262B)


  1. // SPDX-FileCopyrightText: 2022 Haelwenn (lanodan) Monnier <contact+adventofcode@hacktivis.me>
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. use bufio;
  4. use os;
  5. use io;
  6. use fmt;
  7. use strings;
  8. use ascii;
  9. export fn main() void = {
  10. let scores: []u32 = [];
  11. for(true) {
  12. let line = match(bufio::scanline(os::stdin)) {
  13. case let l: []u8 =>
  14. yield l;
  15. case io::EOF =>
  16. break;
  17. case let e: io::error =>
  18. fmt::fatal("day3.0: {}", io::strerror(e));
  19. };
  20. let line = strings::fromutf8(line);
  21. let head = strings::sub(line, 0, len(line)/2);
  22. let tail = strings::sub(line, len(line)/2, strings::end);
  23. let i = strings::iter(head);
  24. let common = ' ': rune;
  25. for(true) {
  26. let dup = match(strings::next(&i)) {
  27. case let r: rune => yield r;
  28. case void => break;
  29. };
  30. if(strings::contains(tail, dup)) {
  31. common = dup;
  32. break;
  33. };
  34. };
  35. let score = if(ascii::islower(common)) {
  36. yield (common: u32)-('a': u32)+1;
  37. } else {
  38. yield (common: u32)-('A': u32)+27;
  39. };
  40. let common = strings::fromrunes([common]);
  41. fmt::printfln("{} | {} -> {}, {}", head, tail, common, score)!;
  42. append(scores, score);
  43. };
  44. let final = 0u32;
  45. for(let i = 0z; i < len(scores); i += 1) {
  46. final += scores[i];
  47. };
  48. fmt::printfln("Score: {}", final)!;
  49. };