summaryrefslogtreecommitdiff
path: root/7.c
diff options
context:
space:
mode:
authorIan C <ianc@noddybox.co.uk>2021-12-09 21:41:11 +0000
committerIan C <ianc@noddybox.co.uk>2021-12-09 21:41:11 +0000
commit466d739f6092eaf0c7f0c5646b19ed65959d268b (patch)
tree7719943de3fe52ca48372836eead36222f5add4a /7.c
parente57f82e16ce6fb903c6568dbc67a78937c0c8fa4 (diff)
Added day 7
Diffstat (limited to '7.c')
-rw-r--r--7.c78
1 files changed, 78 insertions, 0 deletions
diff --git a/7.c b/7.c
new file mode 100644
index 0000000..88da7f1
--- /dev/null
+++ b/7.c
@@ -0,0 +1,78 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+static char *ReadLine(char *p, size_t size, FILE *fp)
+{
+ if ((p=fgets(p, size, fp)))
+ {
+ size_t l = strlen(p);
+
+ while(l && p[l-1] == '\n')
+ {
+ p[--l] = 0;
+ }
+ }
+
+ return p;
+}
+
+static int Distance(int from, int to)
+{
+ return abs(from - to);
+}
+
+int main(void)
+{
+ char buff[0x8000];
+ int *num = NULL;
+ int num_count = 0;
+ char *p = NULL;
+ int min = 2147483647;
+ int max = 0;
+ int f = 0;
+ int n = 0;
+ int lowest = 2147483647;
+
+ ReadLine(buff, sizeof buff, stdin);
+
+ p = strtok(buff, ",");
+
+ while(p)
+ {
+ num = realloc(num, (num_count + 1) * sizeof *num);
+ f = atoi(p);
+
+ if (f > max)
+ {
+ max = f;
+ }
+
+ if (f < min)
+ {
+ min = f;
+ }
+
+ num[num_count++] = f;
+ p = strtok(NULL, ",");
+ }
+
+ for(f = min; f <= max; f++)
+ {
+ int result = 0;
+
+ for(n = 0; n < num_count; n++)
+ {
+ result += Distance(f, num[n]);
+ }
+
+ if (result < lowest)
+ {
+ lowest = result;
+ }
+ }
+
+ printf("lowest = %d\n", lowest);
+
+ return 0;
+}