day1.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int arraySize = 0;
  4. int **readInput(FILE *fp) {
  5. int **array = NULL;
  6. int index = 0;
  7. while (1) {
  8. if (feof(fp)) break;
  9. int *p = malloc(sizeof(int));
  10. if (!p) return NULL;
  11. if (1 != fscanf(fp, "%d\n", p))
  12. return NULL;
  13. arraySize++;
  14. int **newArray = realloc(array, sizeof(int*)*arraySize);
  15. if (!newArray) return NULL;
  16. array = newArray;
  17. array[index] = p;
  18. index++;
  19. }
  20. return array;
  21. }
  22. void freeArray(int **array) {
  23. for (int i = 0; i < arraySize; i++)
  24. free(array[i]);
  25. free(array);
  26. }
  27. void part1(int **array, int target) {
  28. for (int i = 0; i < arraySize; i++) {
  29. int first = *array[i];
  30. int second = target - first;
  31. for (int j = i + 1; j < arraySize; j++) {
  32. if (*array[j] == second) {
  33. printf("Part1: %d\n", first * second);
  34. return;
  35. }
  36. }
  37. }
  38. }
  39. void part2(int **array, int target) {
  40. for (int i = 0; i < arraySize; i++) {
  41. int first = *array[i];
  42. int threshold = target - first;
  43. for (int j = i + 1; j < arraySize; j++) {
  44. if (*array[j] < threshold) {
  45. int third = threshold - *array[j];
  46. for (int k = j + 1; k < arraySize; k++) {
  47. if (*array[k] == third) {
  48. printf("Part1: %d\n", first * *array[j] *third);
  49. return;
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56. int main(int argc, char **argv)
  57. {
  58. if (argc < 2) {
  59. puts("You need to specify path to file!");
  60. return -1;
  61. }
  62. FILE *fp = fopen(argv[1], "r");
  63. if (!fp) {
  64. puts("Can't read");
  65. return -1;
  66. }
  67. int **array = readInput(fp);
  68. if (!array) {
  69. puts("Can't read array!");
  70. return -1;
  71. }
  72. part1(array, 2020);
  73. part2(array, 2020);
  74. fclose(fp);
  75. freeArray(array);
  76. }