aboutsummaryrefslogtreecommitdiff
path: root/2020
diff options
context:
space:
mode:
authorMarvin Borner2020-12-18 13:17:29 +0100
committerMarvin Borner2020-12-18 13:17:29 +0100
commit214a554dcf606e1918e4c0cca22fa31d993c089c (patch)
tree371a625dc62cce461fc70b88d241f1cdd43f4df6 /2020
parentccc76359ae484261758e7bf429b65ef31d646919 (diff)
Argh all test cases pass :O
Diffstat (limited to '2020')
-rw-r--r--2020/18/Makefile10
-rw-r--r--2020/18/input6
-rw-r--r--2020/18/solve.c86
3 files changed, 102 insertions, 0 deletions
diff --git a/2020/18/Makefile b/2020/18/Makefile
new file mode 100644
index 0000000..9c7ab36
--- /dev/null
+++ b/2020/18/Makefile
@@ -0,0 +1,10 @@
+.PHONY: solve.c
+
+solve.o: solve.c
+ @gcc -g -Ofast $+ -o $@
+
+clean:
+ @rm -f *.o
+
+run: solve.o
+ @./solve.o
diff --git a/2020/18/input b/2020/18/input
new file mode 100644
index 0000000..6e33178
--- /dev/null
+++ b/2020/18/input
@@ -0,0 +1,6 @@
+1 + 2 * 3 + 4 * 5 + 6
+1 + (2 * 3) + (4 * (5 + 6))
+2 * 3 + (4 * 5)
+5 + (8 * 3 + 9 + 3 * 4 * 3)
+5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))
+((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
diff --git a/2020/18/solve.c b/2020/18/solve.c
new file mode 100644
index 0000000..b223728
--- /dev/null
+++ b/2020/18/solve.c
@@ -0,0 +1,86 @@
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+long add_or_mul(long *res, int num, int mul)
+{
+ if (mul == 0)
+ *res += num;
+ else
+ *res *= num;
+ return *res;
+}
+
+long evil(char *str)
+{
+ long res = 0;
+ int mul = 0, skip = 0, brace_cnt = 0;
+ for (char *p = str; *p; p++) {
+ if (skip) {
+ if (*p == '(') {
+ brace_cnt++;
+ } else if (*p == ')' && !(brace_cnt--)) {
+ brace_cnt = 0;
+ skip = 0;
+ }
+ continue;
+ }
+
+ if (*p == ' ') {
+ continue;
+ } else if (*p == '(') {
+ add_or_mul(&res, evil(p + 1), mul);
+ skip = 1;
+ } else if (*p == ')') {
+ break; // That's why I don't use switch..case
+ } else if (*p == '*') {
+ mul = 1;
+ } else if (*p == '+') {
+ mul = 0;
+ } else if (isdigit(*p)) {
+ add_or_mul(&res, *p - '0', mul);
+ }
+ }
+ return res;
+}
+
+int part_one(FILE *fp)
+{
+ int res = 0;
+
+ char *line = NULL;
+ size_t len;
+ while (getline(&line, &len, fp) != -1) {
+ int a = evil(line);
+ printf("%d\n", a);
+ res += a;
+ }
+
+ return res;
+}
+
+int part_two(FILE *fp)
+{
+ int res = 0;
+
+ return res;
+}
+
+int main(int argc, char *argv[])
+{
+ FILE *fp = fopen("input", "r");
+ if (!fp)
+ exit(EXIT_FAILURE);
+
+ clock_t tic = clock();
+ printf("%lu\n", part_one(fp));
+ rewind(fp);
+ printf("%lu\n", part_two(fp));
+ clock_t toc = clock();
+ printf("TIME: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
+
+ fclose(fp);
+ return 0;
+}