summaryrefslogtreecommitdiff
path: root/2018/aoc2018-d04.py
blob: 42791fd39219f8c90409132294396c37928f0284 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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);