part2.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include "str.h"
  6. char *numbers[] = {
  7. "zero",
  8. "one",
  9. "two",
  10. "three",
  11. "four",
  12. "five",
  13. "six",
  14. "seven",
  15. "eight",
  16. "nine"
  17. };
  18. int find_number(const char *line) {
  19. int matched = 0;
  20. if (isdigit(*line)) return *line - '0';
  21. for (int i = 0; i < 10; i++) {
  22. matched = 1;
  23. const char *p1 = numbers[i], *p2 = line;
  24. while (*p1 != '\0' && *p2 != '\0') {
  25. if (*p1 != *p2) {
  26. matched = 0;
  27. break;
  28. }
  29. p1++;
  30. p2++;
  31. }
  32. if (matched && *p1 == '\0') return i;
  33. }
  34. return -1;
  35. }
  36. int main() {
  37. FILE* fp = fopen("./input", "r");
  38. int sum = 0;
  39. while (1) {
  40. char *line = str_strip(fgetline(fp));
  41. if (line == NULL || strlen(line) == 0) {
  42. break;
  43. }
  44. int d1 = -1, d2 = -1;
  45. while (*line != '\0') {
  46. int num = -1;
  47. if ((num = find_number(line)) >= 0) {
  48. if (d1 == -1) d1 = num;
  49. d2 = num;
  50. }
  51. line++;
  52. }
  53. if (d2 == -1) d2 = d1;
  54. sum += d1 * 10 + d2;
  55. }
  56. printf("%d\n", sum);
  57. return 0;
  58. }