logo

adventofcode

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

day1.c (1349B)


  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 password = 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. switch(line[0])
  49. {
  50. case 'L':
  51. pos -= rot;
  52. break;
  53. case 'R':
  54. pos += rot;
  55. break;
  56. }
  57. /* Sadly modulo doesn't works for negative inputs */
  58. while(pos < 0) pos += 100;
  59. while(pos > 99) pos -= 100;
  60. printf("%-4s rot:%-4d pos:%d\n", line, rot, pos);
  61. if(pos == 0) password++;
  62. }
  63. free(line);
  64. printf("Result: %d\n", password);
  65. }