Skip to content

Commit

Permalink
Bit nicer 13b
Browse files Browse the repository at this point in the history
  • Loading branch information
estomagordo committed Dec 13, 2018
1 parent a159b9c commit 932c9e9
Showing 1 changed file with 60 additions and 49 deletions.
109 changes: 60 additions & 49 deletions estomagordo-python3/day_13b.py
Original file line number Diff line number Diff line change
@@ -1,73 +1,85 @@
from collections import defaultdict
def make_cart(x, y, c):
cart = [x, y, 0]

if c == '>':
cart.append(0)
elif c == 'v':
cart.append(1)
elif c == '<':
cart.append(2)
else:
cart.append(3)

return cart


def turn(symbol, direction, mode):
if symbol == '/':
if direction == 0:
direction = 3
elif direction == 1:
direction = 2
elif direction == 2:
direction = 1
else:
direction = 0
elif symbol == '\\':
if direction == 0:
direction = 1
elif direction == 1:
direction = 0
elif direction == 2:
direction = 3
else:
direction = 2
elif symbol == '+':
if mode == 0:
direction = (direction - 1) % 4
elif mode == 2:
direction = (direction + 1) % 4
mode = (mode + 1) % 3

return direction, mode


def move(x, y, direction):
if direction == 0:
x += 1
elif direction == 1:
y += 1
elif direction == 2:
x -= 1
else:
y -= 1

return x, y


def solve(d):
moved = defaultdict(int)
carts = []

for y, line in enumerate(d):
for x, c in enumerate(line):
if c not in '>v<^':
continue
carts.append([x, y, 0])
if c == '>':
carts[-1].append(0)
elif c == 'v':
carts[-1].append(1)
elif c == '<':
carts[-1].append(2)
else:
carts[-1].append(3)
steps = 0
carts.append(make_cart(x, y, c))

while True:
mv = set()
removal = []
carts.sort(key=lambda cart: [cart[1], cart[0]])

for cart_number, cart in enumerate(carts):
x, y, mode, direction = carts[cart_number]

if direction == 0:
x += 1
elif direction == 1:
y += 1
elif direction == 2:
x -= 1
else:
y -= 1

moved[cart_number] += 1
x, y, mode, direction = cart
x, y = move(x, y, direction)

for cn, cart in enumerate(carts):
if cart[:2] == [x, y]:
if cn in mv or (cart[3] != direction and not (cart[3] + direction) % 2):
removal.append(cart_number)
removal.append(cn)

if d[y][x] == '/':
if direction == 0:
direction = 3
elif direction == 1:
direction = 2
elif direction == 2:
direction = 1
else:
direction = 0
elif d[y][x] == '\\':
if direction == 0:
direction = 1
elif direction == 1:
direction = 0
elif direction == 2:
direction = 3
else:
direction = 2
elif d[y][x] == '+':
if mode == 0:
direction = (direction - 1) % 4
elif mode == 2:
direction = (direction + 1) % 4
mode = (mode + 1) % 3
direction, mode = turn(d[y][x], direction, mode)

carts[cart_number] = [x, y, mode, direction]
mv.add(cart_number)
Expand All @@ -77,7 +89,6 @@ def solve(d):
if len(carts) == 1:
return ','.join(map(str, carts[0][:2]))

steps += 1

def read_and_solve():
with open('input_13.txt') as f:
Expand Down

0 comments on commit 932c9e9

Please sign in to comment.