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
|
#!/usr/bin/python
class Reindeer:
pass
def parse_input(lines):
result = []
for line in lines:
words = line.split()
r = Reindeer()
r.name = words[0]
r.dist = 0
r.score = 0
r.state = "moving"
r.speed = int(words[ 3])
r.tmove = int(words[ 6])
r.trest = int(words[13])
r.timer = 0
result.append(r)
return result
def solve_partn(partn, lines, tmax):
contestants = parse_input(lines)
for t in range(tmax):
for r in contestants:
if r.state == "moving":
r.dist += r.speed
r.timer += 1
if r.timer >= r.tmove:
r.state = "resting"
r.timer = 0
else: # r.state == "resting"
r.timer += 1
if r.timer >= r.trest:
r.state = "moving"
r.timer = 0
# Award 1 point to leader (and to others in case of a tie)
# Only for part 2, but doesn't hurt part 1, so not disabled.
leader = max(contestants, key = lambda r: r.dist)
for r in contestants:
if r.dist == leader.dist:
r.score += 1
if partn == 1:
winner = max(contestants, key = lambda r: r.dist)
return winner.dist
else: # partn == 2
winner = max(contestants, key = lambda r: r.score)
return winner.score
def main():
# Read reindeer stats from input text file
with open("input.txt", "r") as f:
lines = f.read().splitlines()
print("Part 1 solution:", solve_partn(1, lines, 2503)) # 2640 for me
print("Part 2 solution:", solve_partn(2, lines, 2503)) # 1102 for me
if __name__ == "__main__":
main()
|