From 95294439434c41b59d9370959e1fe368d86fa43b Mon Sep 17 00:00:00 2001 From: Joscha Date: Mon, 3 Dec 2018 09:29:06 +0000 Subject: [PATCH] Solve 2017/03 --- 2017/03/solve.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 2017/03/solve.py diff --git a/2017/03/solve.py b/2017/03/solve.py new file mode 100644 index 0000000..2d544d9 --- /dev/null +++ b/2017/03/solve.py @@ -0,0 +1,64 @@ +import sys + +# PART 1 + +def spiral(nth): + length = 1 + nth -= 1 + x = 0 + y = 0 + while True: + x += min(length, nth) + nth -= min(length, nth) + if nth == 0: return x, y + y += min(length, nth) + nth -= min(length, nth) + if nth == 0: return x, y + + length += 1 + + x -= min(length, nth) + nth -= min(length, nth) + if nth == 0: return x, y + y -= min(length, nth) + nth -= min(length, nth) + if nth == 0: return x, y + + length += 1 + +def manhattan(x, y): + return abs(x) + abs(y) + +# PART 2 + +def store(cap): + stored = {(0, 0): 1} + nth = 2 + while True: + x, y = spiral(nth) + adjacent = 0 + adjacent += stored.get((x-1, y-1), 0) + adjacent += stored.get((x , y-1), 0) + adjacent += stored.get((x+1, y-1), 0) + adjacent += stored.get((x-1, y ), 0) + adjacent += stored.get((x+1, y ), 0) + adjacent += stored.get((x-1, y+1), 0) + adjacent += stored.get((x , y+1), 0) + adjacent += stored.get((x+1, y+1), 0) + stored[(x, y)] = adjacent + nth += 1 + + if adjacent > cap: + return adjacent + +def main(): + nth = 277678 + print(f"Solutions") + x, y = spiral(nth) + dist = manhattan(x, y) + print(f"Part 1: {dist}") + adjacent = store(nth) + print(f"Part 2: {adjacent}") + +if __name__ == "__main__": + main()