part1.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include "str.h"
  6. #include "vec.h"
  7. typedef struct {
  8. int r,g,b;
  9. } set_t;
  10. typedef struct {
  11. int length;
  12. set_t sets[64];
  13. } game_t;
  14. game_t games[100];
  15. void parse_set(const char *str, set_t *set) {
  16. void* strs = str_split(str, ',');
  17. set->r = 0;
  18. set->g = 0;
  19. set->b = 0;
  20. for (int i = 0; i < vec_size(strs); i++) {
  21. char *str = vec_get(strs, i);
  22. void* infos = str_split(str, ' ');
  23. if (strcmp(vec_get(infos, 1), "red") == 0) {
  24. set->r = strtol(vec_get(infos, 0), NULL, 10);
  25. } else if (strcmp(vec_get(infos, 1), "blue") == 0) {
  26. set->b = strtol(vec_get(infos, 0), NULL, 10);
  27. } else if (strcmp(vec_get(infos, 1), "green") == 0) {
  28. set->g = strtol(vec_get(infos, 0), NULL, 10);
  29. }
  30. }
  31. }
  32. void parse_game(const char *line, game_t *game) {
  33. void *strs = str_split(line, ':');
  34. void *sets_str = str_split(vec_get(strs, 1), ';');
  35. for (int i = 0; i < vec_size(sets_str); i++) {
  36. set_t s;
  37. parse_set(str_strip(vec_get(sets_str, i)), &s);
  38. game->sets[i] = s;
  39. }
  40. game->length = vec_size(sets_str);
  41. }
  42. int is_possible(game_t *game) {
  43. for (int i = 0; i < game->length; i++) {
  44. if (game->sets[i].r <= 12
  45. && game->sets[i].g <= 13
  46. && game->sets[i].b <= 14) {
  47. continue;
  48. }
  49. return 0;
  50. }
  51. return 1;
  52. }
  53. int main() {
  54. FILE *fp = fopen("./input", "r");
  55. int sum = 0;
  56. for (int i = 0; i < 100; i++) {
  57. char *line = fgetline(fp);
  58. parse_game(line, &games[i]);
  59. }
  60. for (int i = 0; i < 100; i++) {
  61. if (is_possible(&games[i])) {
  62. sum += i + 1;
  63. }
  64. }
  65. printf("%d\n", sum);
  66. return 0;
  67. }