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!

22 Upvotes

297 comments sorted by

View all comments

Show parent comment

2

u/pja Dec 04 '17

Yours is more "Haskelly" than mine for part2, which was a horrible brute force affair. No need for a HashMap though - Data.Map.Strict is fine, although probably a little slower.

This code returns the value for a given index in the spiral.

import System.Environment
import Numeric
import qualified Data.Map.Strict as M
import Data.Maybe

main = do
  is <- getArgs
  let i = read $ head is
  putStrLn $ show $ manhattan i

manhattan :: Int -> Int
manhattan t = xplus (M.singleton (0,0) 1) 2 t 1 1 (1,0)
    where xplus m c t s s1 (x,y) | c<t && s1<s  = xplus (i (x,y) m) (c+1) t s (s1+1) (x+1,y)
                                 | c<t && s1==s = yplus (i (x,y) m) (c+1) t s 1 (x,y+1)
                                 | otherwise    = fromJust $ M.lookup (x,y) (i (x,y) m)
          xneg m c t s s1 (x,y) | c<t && s1<s  = xneg (i (x,y) m) (c+1) t s (s1+1) (x-1,y)
                                | c<t && s1==s = yneg (i (x,y) m) (c+1) t s 1 (x,y-1)
                                | otherwise    = fromJust $ M.lookup (x,y)  (i (x,y) m)
          yplus m c t s s1 (x,y) | c<t && s1<s  = yplus (i (x,y) m) (c+1) t s (s1+1)  (x,y+1)
                                 | c<t && s1==s = xneg (i (x,y) m) (c+1) t (s+1) 1 (x-1,y)
                                 | otherwise    = fromJust $ M.lookup (x,y)  (i (x,y) m)
          yneg m c t s s1 (x,y) | c<t && s1<s  = yneg (i (x,y) m) (c+1) t s (s1+1)  (x,(y-1))
                                | c<t && s1==s = xplus (i (x,y) m) (c+1) t (s+1) 1 (x+1,y)
                                | otherwise    = fromJust $ M.lookup (x,y)  (i (x,y) m)
          i (x,y) m = M.insert (x,y) (sum $ catMaybes $
                         map ((flip M.lookup) m) [(x1,y1) | x1 <- [x-1,x,x+1],
                                                 y1 <- [y-1,y,y+1],
                                                 not (x1==x && y1==y)]) m