From 474d7a06c6b0334aa6d228372540c3c2ac501306 Mon Sep 17 00:00:00 2001 From: Joscha Date: Mon, 3 Dec 2018 13:27:57 +0000 Subject: [PATCH] Solve 2016/01 --- 2016/01/input.txt | 1 + 2016/01/solve.py | 74 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 2016/01/input.txt create mode 100644 2016/01/solve.py diff --git a/2016/01/input.txt b/2016/01/input.txt new file mode 100644 index 0000000..4b9fef2 --- /dev/null +++ b/2016/01/input.txt @@ -0,0 +1 @@ +L4, R2, R4, L5, L3, L1, R4, R5, R1, R3, L3, L2, L2, R5, R1, L1, L2, R2, R2, L5, R5, R5, L2, R1, R2, L2, L4, L1, R5, R2, R1, R1, L2, L3, R2, L5, L186, L5, L3, R3, L5, R4, R2, L5, R1, R4, L1, L3, R3, R1, L1, R4, R2, L1, L4, R5, L1, R50, L4, R3, R78, R4, R2, L4, R3, L4, R4, L1, R5, L4, R1, L2, R3, L2, R5, R5, L4, L1, L2, R185, L5, R2, R1, L3, R4, L5, R2, R4, L3, R4, L2, L5, R1, R2, L2, L1, L2, R2, L2, R1, L5, L3, L4, L3, L4, L2, L5, L5, R2, L3, L4, R4, R4, R5, L4, L2, R4, L5, R3, R1, L1, R3, L2, R2, R1, R5, L4, R5, L3, R2, R3, R1, R4, L4, R1, R3, L5, L1, L3, R2, R1, R4, L4, R3, L3, R3, R2, L3, L3, R4, L2, R4, L3, L4, R5, R1, L1, R5, R3, R1, R3, R4, L1, R4, R3, R1, L5, L5, L4, R4, R3, L2, R1, R5, L3, R4, R5, L4, L5, R2 diff --git a/2016/01/solve.py b/2016/01/solve.py new file mode 100644 index 0000000..cf04ad8 --- /dev/null +++ b/2016/01/solve.py @@ -0,0 +1,74 @@ +import sys + +def load_steps(filename): + steps = [] + with open(filename, "r") as f: + for step in f.read()[:-1].split(","): + step = step.strip() + step = (step[0], int(step[1:])) + steps.append(step) + return steps + +# PART 1 + +def turn(direction, where): + dir_x, dir_y = direction + + if where == "R": + return (dir_y, -dir_x) + elif where == "L": + return (-dir_y, dir_x) + else: + raise Exception("HEY! Don't do that!") + +def manhattan(position): + x, y = position + return abs(x) + abs(y) + +def find_distance(steps): + pos_x, pos_y = 0, 0 + direction = (1, 0) + + for step in steps: + where, amount = step + direction = turn(direction, where) + dir_x, dir_y = direction + pos_x += dir_x * amount + pos_y += dir_y * amount + + return manhattan((pos_x, pos_y)) + +# PART 2 + +def first_visited_twice(steps): + pos_x, pos_y = 0, 0 + direction = (1, 0) + visited = {(pos_x, pos_y)} + + for step in steps: + where, amount = step + direction = turn(direction, where) + dir_x, dir_y = direction + + for i in range(amount): + pos_x += dir_x + pos_y += dir_y + position = (pos_x, pos_y) + + if position in visited: + return position + else: + visited.add(position) + +def main(filename): + steps = load_steps(filename) + print(f"Solutions for {filename}") + distance = find_distance(steps) + print(f"Part 1: {distance}") + pos = first_visited_twice(steps) + distance_2 = manhattan(pos) + print(f"Part 2: {distance_2}") + +if __name__ == "__main__": + for filename in sys.argv[1:]: + main(filename)