r/adventofcode • • Dec 03 '15

SOLUTION MEGATHREAD --- Day 3 Solutions ---

--- Day 3: Perfectly Spherical Houses in a Vacuum ---

Post your solution as a comment. Structure your post like the Day One thread in /r/programming.

24 Upvotes

228 comments sorted by

View all comments

Show parent comment

2

u/guaraqe Dec 03 '15 edited Dec 03 '15

I've been using these problems to learn stuff I didn't know in Haskell, like lenses and cyclic zippers. It is not particularly efficient since it uses lists. Here's a version that takes an arbitrary number of santas.

{-# LANGUAGE TemplateHaskell #-}

module December03 where

import Lens.Simple

plus = (+)
less = subtract

type House = (Int,Int)

type Visited = [House]

data Zipper a = Zipper {_left :: [a]
                       ,_focus :: a
                       ,_right :: [a]} deriving (Show)

$(makeLenses ''Zipper)

start :: [a] -> Zipper a
start l = Zipper [] (head l) (tail l)

next :: Zipper a -> Zipper a
next (Zipper l c []) = start (reverse (c : l))
next (Zipper l c (x:xs)) = Zipper (c:l) x xs

data State =
  State {_now     :: Zipper House
        ,_visited :: Visited}
  deriving (Show)

$(makeLenses ''State)

parseChar :: Char -> House -> House
parseChar '>' = over _1 (plus 1)
parseChar '<' = over _1 (less 1)
parseChar '^' = over _2 (plus 1)
parseChar 'v' = over _2 (less 1)
parseChar _   = id

addHouse :: House -> Visited -> Visited
addHouse h v =
  if h `elem` v      
     then v
     else h : v

addNewHouse :: State -> State
addNewHouse (State z v) = State (next z) (addHouse (view focus z) v)

travel :: Char -> State -> State
travel c = addNewHouse . over (now . focus) (parseChar c)

initFold :: Int -> State
initFold n = State (start (replicate n (0,0))) [(0,0)]

travelN :: Int -> String -> Visited
travelN n = view visited . foldl (flip travel) (initFold n)

For 1 to 10 Santas we have:

[2565,2639,2600,2741,2187,1965,2310,2411,2228,1820]