summaryrefslogtreecommitdiff
path: root/2018/aoc2018-d04.py
diff options
context:
space:
mode:
Diffstat (limited to '2018/aoc2018-d04.py')
-rw-r--r--2018/aoc2018-d04.py104
1 files changed, 104 insertions, 0 deletions
diff --git a/2018/aoc2018-d04.py b/2018/aoc2018-d04.py
new file mode 100644
index 0000000..42791fd
--- /dev/null
+++ b/2018/aoc2018-d04.py
@@ -0,0 +1,104 @@
+#advent of code 2018
+#day 04
+#part 1 and 2
+
+import numpy as np
+
+def datecompact(log):
+ d = log[1:5] + log[6:8] + log[9:11] + log[12:14] + log[15:17];
+ return int(d);
+
+def action(log):
+ if (log[19] == "f"):
+ return 1;
+ elif (log[19] == "w"):
+ return 2;
+ else:
+ return int(log[24:].strip("\n # begins shift"));
+ return (log[24:].strip("\n # begins shift"));
+
+f = open("04.in","r");
+
+myinput = [];
+guards = {};
+
+for i in f:
+ myinput.append([datecompact(i),action(i)]);
+ if (action(i) != 1 and action(i) != 2 ):
+ try:
+ guards[action(i)] = 0;
+ except:
+ True;
+
+for i in range(len(myinput)):
+ for j in range(len(myinput)):
+ if (myinput[i][0] < myinput[j][0]):
+ temp = myinput[i];
+ myinput[i] = myinput[j];
+ myinput[j] = temp;
+
+x1 = 0;
+for l in myinput:
+ if l[1] == 2:
+ guards[g] += l[0] - x1 ;
+ elif l[1] == 1:
+ x1 = l[0];
+ else:
+ g = l[1];
+
+tmax = 0;
+bestg = "";
+
+for g in guards.keys():
+ if (guards[g] >tmax):
+ tmax = guards[g];
+ bestg = g;
+
+is_bestg = False;
+timestat = np.full(60,0, dtype=int);
+for l in myinput:
+ if (is_bestg and (l[1] == 1 or l[1] == 2)):
+ if l[1] == 1:
+ t1 = l[0];
+ elif l[1] == 2:
+ t2 = l[0];
+ for t in range(t1%100,t2%100,1):
+ timestat[t] += 1;
+ elif l[1] == bestg:
+ is_bestg = True;
+ elif l[1] != bestg:
+ is_bestg = False;
+
+worsttime = (np.argmax(timestat));
+p1 = int(bestg)*worsttime;
+print("part 1 =",p1);
+
+GuardsTimestamps = dict();
+for l in sorted(myinput, key = lambda ts: ts[0]):
+ g_ts, t_code = l;
+ if t_code == 1:
+ SleepStart = 0 + g_ts;
+ elif t_code == 2:
+ SleepEnd = 0 + g_ts;
+ for minute in range(SleepStart%100, SleepEnd%100 + 1):
+ if minute not in GuardsTimestamps[CurrentGuard]:
+ GuardsTimestamps[CurrentGuard][minute] = 0;
+ GuardsTimestamps[CurrentGuard][minute] += 1;
+ else:
+ CurrentGuard = 0 + t_code;
+ if CurrentGuard not in GuardsTimestamps:
+ GuardsTimestamps[CurrentGuard] = dict();
+
+SleepFrequency = [];
+for Guard in GuardsTimestamps:
+ BestMinute = 0;
+ BestMinuteFreq = 0;
+ for ts in GuardsTimestamps[Guard]:
+ if GuardsTimestamps[Guard][ts] > BestMinuteFreq:
+ BestMinuteFreq = GuardsTimestamps[Guard][ts];
+ BestMinute = ts;
+ SleepFrequency.append((Guard,BestMinute,BestMinuteFreq));
+
+MostFrequent = max(SleepFrequency, key = lambda sf: sf[2]);
+p2 = MostFrequent[0]*MostFrequent[1];
+print("part 2 =",p2);