Skip to content

Instantly share code, notes, and snippets.

@rouzbeh
Last active December 13, 2018 11:01
Show Gist options
  • Save rouzbeh/02a6769a9b7ef36966939e9291fa6566 to your computer and use it in GitHub Desktop.
Save rouzbeh/02a6769a9b7ef36966939e9291fa6566 to your computer and use it in GitHub Desktop.
Advent of Code day 13
import heapq
moves = {
"<" : (0, -1),
">" : (0, 1),
"v" : (1, 0),
"^" : (-1, 0),
}
left_turn = {
"<" : "v",
">" : "^",
"v" : ">",
"^" : "<",
}
right_turn = {
"<" : "^",
">" : "v",
"v" : "<",
"^" : ">",
}
virages = {
("<","/") : "v",
(">","/") : "^",
("^","/") : ">",
("v","/") : "<",
(">","\\") : "v",
("<","\\") : "^",
("v","\\") : ">",
("^","\\") : "<",
}
def init():
m = []
carts = {}
pos_carts = []
with open('13', "r") as file:
for i, line in enumerate(file.readlines()):
m.append([])
for j,c in enumerate(line):
if c in ["<",">","v", "^"]:
m[-1].append("-")
carts[(i,j)] = (c,0)
pos_carts.append((i,j))
else:
m[-1].append(c)
heapq.heapify(pos_carts)
return (pos_carts, carts, m)
def view(m):
for l in m:
for c in l:
print(c, end='')
print("")
def turn_intersection(cart):
global left_turn, right_turn
new_direction = cart[0]
if cart[1] == 0:
new_direction = left_turn[cart[0]]
if cart[1] == 2:
new_direction = right_turn[cart[0]]
new_number = (cart[1]+1) % 3
return (new_direction, new_number)
def turn_junction(cart, junction):
global virages
new_direction = virages[(cart[0],junction)]
return (new_direction, cart[1])
def step(pos, m, carts, moves):
new_pos = []
removed = set()
while len(pos)>0:
p = heapq.heappop(pos)
if(p in removed):
continue
cart = carts[p]
move = moves[cart[0]]
new_p = (p[0]+move[0], p[1]+move[1])
try:
assert(new_p[0]>=0)
assert(new_p[1]>=0)
except AssertionError:
print("SHIT", p, new_p, move)
return ([], [])
new_cart = cart
if m[new_p[0]][new_p[1]] == "+":
new_cart = turn_intersection(cart)
if m[new_p[0]][new_p[1]] in ["/","\\"]:
new_cart = turn_junction(cart, m[new_p[0]][new_p[1]])
del carts[p]
if new_p in carts.keys():
print("Crash at {}, {}".format(new_p[1], new_p[0]))
del carts[new_p]
if new_p in new_pos:
new_pos.remove(new_p)
removed.add(new_p)
removed.add(p)
else:
new_pos.append(new_p)
carts[new_p] = new_cart
return (new_pos, carts)
(pos_carts, carts, m) = init()
while len(pos_carts)>1:
pos_carts, carts = step(pos_carts, m, carts, moves)
print(pos_carts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment