r/adventofcode • • Dec 05 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 5 Solutions -๐ŸŽ„-

--- Day 5: A Maze of Twisty Trampolines, All Alike ---


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

403 comments sorted by

View all comments

1

u/matusbzk Dec 09 '17 edited Dec 16 '17

Haskell

Actually, this one is really inefficient. Calculates the first part in like 6 seconds, but the second part takes more then 10 minutes (then I closed it). I calculated the actual solution in C#. But I found some Haskell solution here.

import Data.List

inputString :: String

-- |Input as a list of ints
input :: [Int]
input = map read . lines $ inputString

-- |Stores current position and a list of instructions
type State = (Int, [Int])

-- |From what state do I begin
startState :: State
startState = (0,input)

-- |Checks whether given state is valid (returns false if program reached the exit)
validState :: State -> Bool
validState (pos,jumps) = pos >= 0 && pos < length jumps

-- |Takes a state and performs one instruction
makeJump :: State -> State
makeJump (position, jumps) = (position + dif, newJumps)
   where dif = jumps !! position
      newJumps = take position jumps ++ (dif+1) : drop (position + 1) jumps

-- |How many steps does it take to reach the exit - result to part 1
-- |Not very effective, takes me like 6 seconds
stepsUntilExit :: Int
stepsUntilExit = fst $ stepsUntilExit' (0,startState)

-- |Iterates a makeJump function, with checking if state is valid
stepsUntilExit' :: (Int, State) -> (Int, State)
stepsUntilExit' (n,state) = if validState state then stepsUntilExit' (n+1, makeJump state) 
            else (n,state)

-- |Takes a state and performs one instruction - version for part 2
makeJump2 :: State -> State
makeJump2 (position, jumps) = (position + dif, newJumps)
   where dif = jumps !! position
      newDif = if dif >= 3 then dif - 1 else dif + 1 
      newJumps = take position jumps ++ [newDif] ++ drop (position + 1) jumps

-- |How many steps does it take to reach the exit - result to part 2
-- |Actually inefficient af, I have calculated the result in C#
-- |Takes more than 10 minutes
stepsUntilExit2 :: Int
stepsUntilExit2 = fst $ stepsUntilExit2' (0,startState)

-- |Iterates a makeJump2 function, with checking if state is valid
stepsUntilExit2' :: (Int, State) -> (Int, State)
stepsUntilExit2' (n,state) = if validState state then stepsUntilExit2' (n+1, makeJump2 state) 
             else (n,state)

Link to git