day2.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <stdio.h>
  2. #define PASS_MAX 50
  3. void part1(FILE *fp) {
  4. int validCount = 0;
  5. while (1) {
  6. if (feof(fp)) break;
  7. int from, to;
  8. char check;
  9. char password[PASS_MAX];
  10. if (4 != fscanf(fp, "%d-%d %c: %s\n", &from, &to, &check, password))
  11. return;
  12. int index = 0;
  13. int checkCount = 0;
  14. while (1) {
  15. if (password[index] == '\0') break;
  16. if (password[index] == check) checkCount++;
  17. if (checkCount > to) break;
  18. index++;
  19. }
  20. if (checkCount >= from && checkCount <= to)
  21. validCount++;
  22. }
  23. printf("Part1: %d\n", validCount);
  24. }
  25. void part2(FILE *fp) {
  26. int validCount = 0;
  27. while (1) {
  28. if (feof(fp)) break;
  29. int from, to;
  30. char check;
  31. char password[PASS_MAX];
  32. if (4 != fscanf(fp, "%d-%d %c: %s\n", &from, &to, &check, password))
  33. return;
  34. if (password[to-1] == check ^ password[from-1] == check) validCount++;
  35. }
  36. printf("Part2: %d\n", validCount);
  37. }
  38. int main(int argc, char **argv)
  39. {
  40. if (argc < 2) {
  41. puts("You need to specify path to file!");
  42. return -1;
  43. }
  44. FILE *fp = fopen(argv[1], "r");
  45. if (!fp) {
  46. puts("Can't read");
  47. return -1;
  48. }
  49. part1(fp);
  50. rewind(fp);
  51. part2(fp);
  52. fclose(fp);
  53. }