day9.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int arraySize = 0;
  4. int checkNumber(int number, int **array, int last) {
  5. for (int i = 0; i < last; i++)
  6. for (int j = i + 1; j < last; j++) {
  7. if ((*array[i] + *array[j]) == number) {
  8. return 1;
  9. }
  10. }
  11. return 0;
  12. }
  13. int findNumber(int **allNumbers, int last) {
  14. int tempArray[last];
  15. for (int i = 0; i < last; i++)
  16. tempArray[i] = *allNumbers[i];
  17. int start = 0;
  18. int index = last;
  19. while (index < arraySize) {
  20. int number = *allNumbers[index];
  21. if (!checkNumber(number, &allNumbers[start++], last)) return number;
  22. index++;
  23. }
  24. return -1;
  25. }
  26. int **readAllNumbers(FILE *fp) {
  27. int **allNumbers = NULL;
  28. int index = 0;
  29. while (1) {
  30. int *p = malloc(sizeof(int));
  31. if (!p) return NULL;
  32. if (1 > fscanf(fp, "%d\n", p))
  33. return NULL;
  34. arraySize++;
  35. int **newNumbers = realloc(allNumbers, sizeof(int*)*arraySize);
  36. if (!newNumbers) return NULL;
  37. allNumbers = newNumbers;
  38. allNumbers[index] = p;
  39. index++;
  40. if (feof(fp)) break;
  41. }
  42. return allNumbers;
  43. }
  44. int encryptionWeakness(int badNumber, int **allNumbers) {
  45. for (int i = 0; i < arraySize; i++) {
  46. int sum = *allNumbers[i];
  47. int smallest = *allNumbers[i];
  48. int largest = *allNumbers[i];
  49. for (int j = i + 1; j < arraySize; j++) {
  50. sum += *allNumbers[j];
  51. smallest = smallest < *allNumbers[j] ? smallest : *allNumbers[j];
  52. largest = largest > *allNumbers[j] ? largest : *allNumbers[j];
  53. if (sum == badNumber) return smallest + largest;
  54. }
  55. }
  56. return -1;
  57. }
  58. void freeAllNumbers(int **array) {
  59. for (int i = 0; i < arraySize; i++)
  60. free(array[i]);
  61. free(array);
  62. }
  63. int main(int argc, char **argv)
  64. {
  65. if (argc < 3) {
  66. puts("You need to specify path to file and preamble length!");
  67. return -1;
  68. }
  69. int last = atoi(argv[2]);
  70. FILE *fp = fopen(argv[1], "r");
  71. if (!fp) {
  72. puts("Can't read");
  73. return -1;
  74. }
  75. int **allNumbers = readAllNumbers(fp);
  76. if (!allNumbers) {
  77. puts("Can't read numbers!");
  78. fclose(fp);
  79. return -1;
  80. }
  81. int badNumber = findNumber(allNumbers, last);
  82. printf("Part1: %d\n", badNumber);
  83. printf("Part2: %d\n", encryptionWeakness(badNumber, allNumbers));
  84. freeAllNumbers(allNumbers);
  85. fclose(fp);
  86. }