day6.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #define NO_ANSWERS 26
  6. int countChecks1(int *checks) {
  7. int count = 0;
  8. for (int i = 0; i < NO_ANSWERS; i++) {
  9. if (checks[i] > 0) count++;
  10. }
  11. return count;
  12. }
  13. int countChecks2(int *checks, int groupSize) {
  14. int count = 0;
  15. for (int i = 0; i < NO_ANSWERS; i++) {
  16. if (checks[i] == groupSize) count++;
  17. }
  18. return count;
  19. }
  20. void zeroChecks(int *checks) {
  21. for (int i = 0; i < NO_ANSWERS; i++)
  22. checks[i] = 0;
  23. }
  24. int readInput(char *path) {
  25. FILE *fp = fopen(path, "r");
  26. if (!fp) {
  27. puts("Can't read");
  28. return -1;
  29. }
  30. int checks[NO_ANSWERS];
  31. zeroChecks(checks);
  32. int sum1 = 0;
  33. int sum2 = 0;
  34. int groupSize = 0;
  35. while (1) {
  36. char * line = NULL;
  37. size_t len = 0;
  38. ssize_t length = getline(&line, &len, fp);
  39. if ((length == 1 && line[0] == '\n') || feof(fp)) {
  40. sum1 += countChecks1(checks);
  41. sum2 += countChecks2(checks, groupSize);
  42. zeroChecks(checks);
  43. groupSize = 0;
  44. } else {
  45. groupSize++;
  46. for (int i = 0; i < length-1; i++) {
  47. int index = line[i]-97;
  48. checks[index]++;
  49. }
  50. }
  51. if (feof(fp)) break;
  52. }
  53. printf("Part1: %d\n", sum1);
  54. printf("Part2: %d\n", sum2);
  55. return 1;
  56. }
  57. int main(int argc, char **argv)
  58. {
  59. if (argc < 2) {
  60. puts("You need to specify path to file!");
  61. return -1;
  62. }
  63. if (!readInput(argv[1])) {
  64. puts("Can't read array!");
  65. return -1;
  66. }
  67. }