2016-12-01 - No Time for a Taxicab
(original .ipynb)
puzzle_input_str = open("puzzle_input/day1.txt").read()
def left(dr, dc):
return (-dc, dr)
def right(dr, dc):
return (dc, -dr)
def turn(direction, dr, dc):
if direction == "R":
return right(dr, dc)
else:
return left(dr, dc)
def parse_input(input_str):
for line in input_str.split(", "):
yield line[0], int(line[1:])
def part_one(input_str):
r, c = 0, 0
dr, dc = -1, 0
for direction, distance in parse_input(input_str):
dr, dc = turn(direction, dr, dc)
r += (distance * dr)
c += (distance * dc)
return abs(r) + abs(c)
assert 5 == part_one("R2, L3")
assert 2 == part_one("R2, R2, R2")
assert 12 == part_one("R5, L5, R5, R3")
print("part one:", part_one(puzzle_input_str))
part one: 234
def part_two(input_str):
commands = input_str.split(", ")
r, c = 0, 0
dr, dc = -1, 0
visited = set()
for direction, distance in parse_input(input_str):
dr, dc = turn(direction, dr, dc)
while distance > 0:
distance -= 1
r += dr
c += dc
if (r,c) in visited:
return abs(r) + abs(c)
visited.add((r,c))
raise Exception("No point was hit more than once")
assert 4 == part_two("R8, R4, R4, R8")
print("part two:", part_two(puzzle_input_str))
part two: 113