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/[deleted] Dec 04 '17

Took me all day yesterday and today to figure this out, I could see the pattern, but translating my idea into Haskell took a while of trial and error

import Data.List

subtract_until diff max (posx, posy) = 
    if diff > 0
    then func
        (if (posy == max && posx > (-max)) then (posx-1, posy)
        else if (posx == (-max) && posy > (-max)) then (posx, posy-1)
        else if (posy == (-max) && posx < max) then (posx+1, posy)
        else (posx, posy+1))
    else (posx, posy)
    where
    func (a, b) = subtract_until (diff-1) max (a, b)

spiral n = 
    abs (fst coords) + abs (snd coords)
    where
    coords = subtract_until (max_corner - n) ind (ind, ind)
    Just ind = elemIndex max_corner corners
    max_corner = head [x | x <- corners, x >= n]
    corners = map (^2) [1,3..]

getNext (x,y)
    | x ==  y && x >= 0 && y >= 0 = (x + 1, y)
    | x ==  c && y > -c = (x, y - 1)
    | y == -c && x > -c = (x - 1, y)
    | x == -c && y <  c = (x, y + 1)
    | y ==  c && x <  c = (x + 1, y)
    | otherwise = (0,0)
    where
    c = max (abs x) (abs y)

coords = iterate getNext (0,0)

find_before c = head [init x | x <- inits coords, x /= [], last x == c]

check_next_to (x,y) (x1,y1)
    | a < 2 && b < 2 = True
    | otherwise = False
    where
    a = abs (x - x1)
    b = abs (y - y1)

calc_before (x,y)
    | (x,y) == (0,0) = 1
    | otherwise  = sum $ map calc_before (filter (check_next_to (x,y)) (find_before (x,y)))

spiral' n =
    head [calc_before x | x <- coords, (calc_before x) > n]

main = do
    x <- readFile("input.txt")
    print ("First star: "++ show (spiral (read(x) :: Integer)))
    print ("Second star: "++ show (spiral' (read(x) :: Integer)))