commit b1019419e368d387c5182c277c4e8710b035e446
parent f2dbf28049e8872ea0923af72a415825eb583e76
Author: Jake Bauer <jbauer@paritybit.ca>
Date: Thu, 16 Dec 2021 14:40:24 -0500
Complete Day 1 challenges
Diffstat:
M | README.md | | | 3 | +++ |
A | main1.c | | | 46 | ++++++++++++++++++++++++++++++++++++++++++++++ |
A | main2.c | | | 68 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
3 files changed, 117 insertions(+), 0 deletions(-)
diff --git a/README.md b/README.md
@@ -3,3 +3,6 @@
Each day is tagged with a git tag.
Compile the code with `cc main.c` and run with `./a.out`.
+
+Some days may have multiple challenges, the first would be in `main1.c`, the
+second in `main2.c` and so on.
diff --git a/main1.c b/main1.c
@@ -0,0 +1,46 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+FILE *
+openInputFile(void)
+{
+ FILE *fp = fopen("input.txt","r");
+ if (fp == NULL)
+ {
+ printf("Could not open file: input.txt\n");
+ exit(EXIT_FAILURE);
+ }
+ return fp;
+}
+
+int
+main(void)
+{
+ char *line = NULL;
+ int increases = 0;
+ int currentValue = 0;
+ int previousValue = -1;
+ size_t len = 0;
+ ssize_t read;
+
+ FILE *fp = openInputFile();
+
+ while ((read = getline(&line, &len, fp)) != -1)
+ {
+ if (previousValue < 0)
+ previousValue = atoi(line);
+
+ currentValue = atoi(line);
+
+ if (currentValue > previousValue)
+ increases++;
+
+ previousValue = currentValue;
+ }
+
+ fclose(fp);
+ if (line)
+ free(line);
+ printf("%d\n", increases);
+ exit(EXIT_SUCCESS);
+}
diff --git a/main2.c b/main2.c
@@ -0,0 +1,68 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+#define ARR_SIZE 3
+
+FILE *
+openInputFile(void)
+{
+ FILE *fp = fopen("input.txt","r");
+ if (fp == NULL)
+ {
+ printf("Could not open file: input.txt\n");
+ exit(EXIT_FAILURE);
+ }
+ return fp;
+}
+
+int
+sumArray(int *array, int size)
+{
+ int sum = 0;
+ for (int i = 0; i < size; i++)
+ sum += array[i];
+ return sum;
+}
+
+int
+main(void)
+{
+ FILE *fp = openInputFile();
+ int increases = 0;
+
+ int array[ARR_SIZE] = { 0 };
+ int arrayPosition = 0;
+ int currentSum = 0;
+ int previousSum = 0;
+ int firstFill = 1;
+
+ char *line = NULL;
+ size_t len = 0;
+ ssize_t read;
+ while ((read = getline(&line, &len, fp)) != -1)
+ {
+ if (arrayPosition == ARR_SIZE) {
+ if (firstFill)
+ previousSum = currentSum;
+ firstFill = 0;
+ arrayPosition = 0;
+ }
+
+ currentSum = sumArray(array, ARR_SIZE);
+ array[arrayPosition++] = atoi(line);
+
+ // Don't do comparisons until we've filled the array
+ if (firstFill)
+ continue;
+
+ if (currentSum > previousSum)
+ increases++;
+ previousSum = currentSum;
+ }
+
+ fclose(fp);
+ if (line)
+ free(line);
+ printf("%d\n", increases);
+ exit(EXIT_SUCCESS);
+}