Solve day 9 till 11 and part 1 day 12 2018
This commit is contained in:
73
2018/d9.py
Normal file
73
2018/d9.py
Normal file
@@ -0,0 +1,73 @@
|
||||
from lib import str_to_ints
|
||||
from collections import defaultdict
|
||||
|
||||
|
||||
def part_1(data):
|
||||
scores = defaultdict(int)
|
||||
n_players, worth = str_to_ints(data)
|
||||
current_player = 0
|
||||
circle = [0]
|
||||
current = 1
|
||||
for n in range(1, worth + 1):
|
||||
if n % 23 == 0:
|
||||
scores[current_player] += n
|
||||
current = (current - 7) % len(circle)
|
||||
scores[current_player] += circle.pop(current)
|
||||
else:
|
||||
current = (current + 2) % len(circle)
|
||||
circle.insert(current, n)
|
||||
current_player = (current_player + 1) % n_players
|
||||
print(max(scores.values()))
|
||||
|
||||
|
||||
class Node:
|
||||
def __init__(self, value, prev=None, next=None):
|
||||
self.value = value
|
||||
if prev is None:
|
||||
self.prev = self
|
||||
else:
|
||||
self.prev = prev
|
||||
if next is None:
|
||||
self.next = self
|
||||
else:
|
||||
self.next = next
|
||||
|
||||
|
||||
def part_2(data):
|
||||
scores = defaultdict(int)
|
||||
n_players, worth = str_to_ints(data)
|
||||
current_player = 0
|
||||
first = Node(0)
|
||||
current = first
|
||||
current.next = current
|
||||
current.prev = current
|
||||
|
||||
for n in range(1, (worth * 100) + 1):
|
||||
if n % 23 == 0:
|
||||
scores[current_player] += n
|
||||
for _ in range(7):
|
||||
current = current.prev
|
||||
scores[current_player] += current.value
|
||||
current.prev.next = current.next
|
||||
current.next.prev = current.prev
|
||||
current = current.next
|
||||
else:
|
||||
new_current = Node(n, current.next, current.next.next)
|
||||
current.next.next.prev = new_current
|
||||
current.next.next = new_current
|
||||
current = new_current
|
||||
current_player = (current_player + 1) % n_players
|
||||
|
||||
print(max(scores.values()))
|
||||
|
||||
|
||||
def main():
|
||||
input_file = __file__.replace(".py", ".txt")
|
||||
with open(input_file) as f:
|
||||
data = f.read()
|
||||
part_1(data)
|
||||
part_2(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user