From 500bc234476c313f5ed9db2ce3ddee7b0a852db5 Mon Sep 17 00:00:00 2001 From: Sebastian Seedorf Date: Sat, 12 Dec 2020 12:02:09 +0100 Subject: [PATCH] Day 12 (complex numbers) --- day12/part1.py | 31 +++++++------------------------ day12/part2.py | 31 +++++++------------------------ 2 files changed, 14 insertions(+), 48 deletions(-) diff --git a/day12/part1.py b/day12/part1.py index c656839..e177190 100644 --- a/day12/part1.py +++ b/day12/part1.py @@ -1,34 +1,17 @@ -import numpy as np - lines = ((x[0], int(x[1:].strip())) for x in open("input.txt")) -pos = np.array([0, 0], dtype=np.int32) -drctn = np.array([1, 0], dtype=np.int32) -targets = np.array([ - [0, 1], - [1, 0], - [0, -1], - [-1, 0] -], dtype=np.int32) +pos = 0 +drctn = 1 +targets = [1j, 1, -1j, -1] target_str = "NESW" - -def direction(target): - return targets[target_str.index(target)] - - -def rotate(current, amount): - angle = np.arctan2(current[1], current[0]) + np.pi / 180 * amount - amount = np.linalg.norm(current) - return np.array([np.rint(np.cos(angle) * amount), np.rint(np.sin(angle) * amount)], dtype=np.int32) - - for line in lines: if line[0] in target_str: - pos += direction(line[0]) * line[1] + pos += targets[target_str.index(line[0])] * line[1] elif line[0] in "LR": - drctn = rotate(drctn, -line[1] if line[0] == "R" else line[1]) + times = (-line[1] if line[0] == "R" else line[1]) / 90 + drctn = drctn * 1j ** times else: pos += drctn * line[1] -print(sum(np.abs(pos))) +print(int(abs(pos.real) + abs(pos.imag))) diff --git a/day12/part2.py b/day12/part2.py index d150eca..53a4864 100644 --- a/day12/part2.py +++ b/day12/part2.py @@ -1,34 +1,17 @@ -import numpy as np - lines = ((x[0], int(x[1:].strip())) for x in open("input.txt")) -pos = np.array([0, 0], dtype=np.int32) -drctn = np.array([10, 1], dtype=np.int32) -targets = np.array([ - [0, 1], - [1, 0], - [0, -1], - [-1, 0] -], dtype=np.int32) +pos = 0 +drctn = 10+1j +targets = [1j, 1, -1j, -1] target_str = "NESW" - -def direction(target): - return targets[target_str.index(target)] - - -def rotate(current, amount): - angle = np.arctan2(current[1], current[0]) + np.pi / 180 * amount - amount = np.linalg.norm(current) - return np.array([np.rint(np.cos(angle) * amount), np.rint(np.sin(angle) * amount)], dtype=np.int32) - - for line in lines: if line[0] in target_str: - drctn += direction(line[0]) * line[1] + drctn += targets[target_str.index(line[0])] * line[1] elif line[0] in "LR": - drctn = rotate(drctn, -line[1] if line[0] == "R" else line[1]) + times = (-line[1] if line[0] == "R" else line[1]) / 90 + drctn = drctn * 1j ** times else: pos += drctn * line[1] -print(sum(np.abs(pos))) +print(int(abs(pos.real) + abs(pos.imag)))