r/adventofcode • • Dec 03 '17

SOLUTION MEGATHREAD -πŸŽ„- 2017 Day 3 Solutions -πŸŽ„-

--- Day 3: Spiral Memory ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Need a hint from the Hugely* Handy† Haversack‑ of HelpfulΒ§ Hints^Β€?

Spoiler


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

21 Upvotes

297 comments sorted by

View all comments

1

u/jwpeddle Dec 06 '17 edited Dec 06 '17

Day 3 Part 2, Python 3

coords = {}

edge = 1
x, y = 0, 0

coords[(x, y)] = 1

class FoundTarget(Exception):
    pass

def update_coords(x, y):
    coords[(x, y)] = get_adjacent_sum(x, y)
    print(x, y, coords[(x, y)])
    if coords[(x, y)] > INPUT:
        raise FoundTarget()

def get_adjacent_sum(x, y):
    adjacent = [
        (x + 1, y + 1),
        (x + 1, y - 1),
        (x - 1, y + 1),
        (x - 1, y - 1),
        (x + 1, y),
        (x - 1, y),
        (x, y + 1),
        (x, y - 1),
    ]
    return sum(
        [coords.get(c, 0) for c in adjacent],
    )

while True:
    edge += 2
    try:
        x += 1
        update_coords(x, y)
        while y < (edge // 2):
            y += 1
            update_coords(x, y)
        while x > -(edge // 2):
            x -= 1
            update_coords(x, y)
        while y > -(edge // 2):
            y -= 1
            update_coords(x, y)
        while x < (edge // 2):
            x += 1
            update_coords(x, y)
    except FoundTarget:
        print(coords[(x, y)])
        break