summaryrefslogtreecommitdiff
path: root/10/part1.c
diff options
context:
space:
mode:
authorBond_009 <bond.009@outlook.com>2020-12-10 15:09:11 +0100
committerBond_009 <bond.009@outlook.com>2020-12-10 15:09:11 +0100
commitc45c08811c6f41d84871f6a83a7317da042feb51 (patch)
treeba40573caef7b9e9d079ed6e828bc1051e912e65 /10/part1.c
parent163b492a26c2d21cf8d20e089c14e8ffe0181578 (diff)
Add day 10
Diffstat (limited to '10/part1.c')
-rw-r--r--10/part1.c73
1 files changed, 73 insertions, 0 deletions
diff --git a/10/part1.c b/10/part1.c
new file mode 100644
index 0000000..9b44cf5
--- /dev/null
+++ b/10/part1.c
@@ -0,0 +1,73 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <malloc.h>
+#include <string.h>
+
+#define MAX_INPUT_LEN 128
+
+void insert_value_sorted(int *list, size_t *size, int value)
+{
+ long long low = 0, high = *size;
+ while (low < high) {
+ int m = low + (high - low) / 2;
+ if (list[m] == value) {
+ /* Name already exists,
+ return pointer to the already existsing string and free the new one.
+ */
+ return;
+ }
+ else if (list[m] < value) {
+ low = m + 1;
+ }
+ else {
+ high = m;
+ }
+ }
+
+ for (long long i = *size - 1; i >= low; i--) {
+ list[i + 1] = list[i];
+ }
+
+ (*size)++;
+ list[low] = value;
+}
+
+int bags_count(const char *filename)
+{
+ FILE *file = fopen(filename, "r");
+
+ // Include space for newline and string terminator
+ char buffer[128] = { 0 };
+
+ int input[MAX_INPUT_LEN] = { 0 };
+ size_t input_size = 1; // 0 is our start value
+
+ while (fgets(buffer, 128, file)) {
+ puts(buffer);
+ insert_value_sorted(input, &input_size, atoi(buffer));
+ }
+
+ fclose(file);
+
+ int diff1 = 0;
+ int diff3 = 1; // Diff with adapter
+
+ for (size_t i = 1; i < input_size; i++)
+ {
+ int diff = input[i] - input[i - 1];
+ if (diff == 1) {
+ diff1++;
+ }
+ else if (diff == 3) {
+ diff3++;
+ }
+ }
+
+ return diff1 * diff3;
+}
+
+int main(int argc, char *argv[])
+{
+ printf("%i\n", bags_count(argv[argc - 1]));
+}