From 6d5b4c80ddf6157b9471eb681da3bea187a34577 Mon Sep 17 00:00:00 2001 From: Yuchen Pei Date: Wed, 6 Dec 2017 16:32:51 +0100 Subject: finished Puzzle3, 4 and 5 part 1 --- Puzzle3.hs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'Puzzle3.hs') diff --git a/Puzzle3.hs b/Puzzle3.hs index 4076ace..0f6c55e 100644 --- a/Puzzle3.hs +++ b/Puzzle3.hs @@ -1,5 +1,28 @@ +import Data.Maybe (fromJust) +import Data.List (elemIndex) +import Control.Monad (liftM2) + f :: Int -> Int f n = floor $ (sqrt (fromIntegral n - 0.5) + 1) / 2 solve1 :: Int -> Int solve1 n = let k = f n in abs ((n - 2 - (2 * k - 1)) `mod` (2 * k) - k) + k + +-- Second puzzle adapted from u/bblum's solution at https://www.reddit.com/r/adventofcode/comments/7h7ufl/2017_day_3_solutions/dqpq2uz/ + +walk :: Int -> Int -> Int -> [Int] +walk n from to | to > 0 = replicate n from ++ [from, from + 1 .. to - 1] ++ walk (n + 1) to (-to) +walk n from to | to < 0 = replicate n from ++ [from, from - 1 .. to + 1] ++ walk (n + 1) to (1 - to) + +-- in walk 0 0 1 for x axis: walk n from to: to > 0: replicate n from builds the right wall, [from, from + 1 .. to - 1] builds the ceiling; n < 0: the replicate bit builds the left wall and the [..] bit builds the floor. +spiral :: [(Int, Int)] +spiral = zipWith (,) (walk 0 0 1) (walk 1 0 1) + +sumList :: [Int] -> [Int] +sumList xs = let m = length xs in xs ++ [sum $ map (\n -> if n < m then xs !! n else 0) $ neighbours (spiral !! m)] + +neighbours :: (Int, Int) -> [Int] +neighbours (x, y) = fromJust . flip elemIndex spiral <$> liftM2 (,) [x - 1 .. x + 1] [y - 1 .. y + 1] + +solve2 :: Int -> Int +solve2 x = last $ until ((>x) . last) sumList [1] -- cgit v1.2.3