logo

adventofcode

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

day3.1.ha (1484B)


  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. fn getline() ([]u8 | void) = {
  10. return match(bufio::scanline(os::stdin)) {
  11. case let l: []u8 =>
  12. yield l;
  13. case io::EOF =>
  14. yield void;
  15. case let e: io::error =>
  16. fmt::fatal("day3.1: {}", io::strerror(e));
  17. };
  18. };
  19. export fn main() void = {
  20. let scores: []u32 = [];
  21. for(true) {
  22. let line1 = match(getline()) {
  23. case let l: []u8 => yield strings::fromutf8(l);
  24. case => break;
  25. };
  26. let line2 = match(getline()) {
  27. case let l: []u8 => yield strings::fromutf8(l);
  28. case => break;
  29. };
  30. let line3 = match(getline()) {
  31. case let l: []u8 => yield strings::fromutf8(l);
  32. case => break;
  33. };
  34. let i = strings::iter(line1);
  35. let common = ' ': rune;
  36. for(true) {
  37. let dup = match(strings::next(&i)) {
  38. case let r: rune => yield r;
  39. case void => break;
  40. };
  41. if(strings::contains(line2, dup)) {
  42. if(strings::contains(line3, dup)) {
  43. common = dup;
  44. break;
  45. };
  46. };
  47. };
  48. let score = if(ascii::islower(common)) {
  49. yield (common: u32)-('a': u32)+1;
  50. } else {
  51. yield (common: u32)-('A': u32)+27;
  52. };
  53. let common = strings::fromrunes([common]);
  54. fmt::printfln("{}, {}", common, score)!;
  55. append(scores, score);
  56. };
  57. let final = 0u32;
  58. for(let i = 0z; i < len(scores); i += 1) {
  59. final += scores[i];
  60. };
  61. fmt::printfln("Score: {}", final)!;
  62. };