logo

adventofcode

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

day1_2.c (1433B)


  1. // SPDX-FileCopyrightText: 2025 Haelwenn (lanodan) Monnier
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #define _POSIX_C_SOURCE 202405L
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <errno.h>
  7. int
  8. main(void)
  9. {
  10. int pos = 50; // The dial starts by pointing at 50
  11. int pass = 0;
  12. char *line = NULL;
  13. size_t linez = 0;
  14. while(1)
  15. {
  16. errno = 0;
  17. ssize_t nread = getline(&line, &linez, stdin);
  18. if(nread < 0)
  19. {
  20. if(errno != 0)
  21. {
  22. perror("getline");
  23. free(line);
  24. return 1;
  25. }
  26. break;
  27. }
  28. if(line[nread-1] == '\n')
  29. line[nread-1] = '\0';
  30. if(line[0] != 'L' && line[0] != 'R')
  31. {
  32. fprintf(stderr, "Got %c instead of [LR]\n", line[0]);
  33. free(line);
  34. return 1;
  35. }
  36. if(line[1] < '0' || line[1] > '9')
  37. {
  38. fprintf(stderr, "Got %c instead of [0-9] as first digit\n", line[0]);
  39. free(line);
  40. return 1;
  41. }
  42. int rot = line[1] - '0';
  43. for(int i = 2; i < nread; i++)
  44. {
  45. if(line[i] < '0' || line[i] > '9') break;
  46. rot = (rot*10) + (line[i] - '0');
  47. }
  48. /* brute-force it rather than math it out */
  49. switch(line[0])
  50. {
  51. case 'L':
  52. for(int a = rot; a > 0; a--)
  53. {
  54. pos = pos == 0 ? 99 : pos-1;
  55. if(pos == 0) pass++;
  56. }
  57. break;
  58. case 'R':
  59. for(int a = rot; a > 0; a--)
  60. {
  61. pos = pos == 99 ? 0 : pos+1;
  62. if(pos == 0) pass++;
  63. }
  64. break;
  65. }
  66. printf("%-4s rot:%-4d pos:%-2d pass:%d\n", line, rot, pos, pass);
  67. }
  68. free(line);
  69. printf("Result: %d\n", pass);
  70. }