diff options
Diffstat (limited to 'Puzzle3.hs')
-rw-r--r-- | Puzzle3.hs | 23 |
1 files changed, 23 insertions, 0 deletions
@@ -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] |