Skip to content

Instantly share code, notes, and snippets.

@reasonableperson
Created April 16, 2016 04:33
Show Gist options
  • Save reasonableperson/5621042a609b52010c18565861fbf328 to your computer and use it in GitHub Desktop.
Save reasonableperson/5621042a609b52010c18565861fbf328 to your computer and use it in GitHub Desktop.
Revenge of the Pancakes (Google Code Jam 2016, Qualification Round, Problem B)
import Data.List
-- Code Jam boilerplate
main :: IO ()
main = getContents >>= putStr . showCases . tail . lines
showCase :: (Int, String) -> String
showCase (i, c) = "Case #" ++ show i ++ ": " ++ show (solve c)
showCases :: [String] -> String
showCases cs = unlines $ map showCase $ zip [1..] cs
-- Solution
type Pancake = Bool
type Stack = [Pancake]
type Flips = Int
parse :: String -> Stack
parse xs = [c == '+' | c <- xs]
flip' :: Stack -> Int -> Stack
flip' xs n = reverse (map not $ take n xs) ++ (drop n xs)
flipTop :: Stack -> Stack
flipTop s = case elemIndex (not $ head s) s of
Just index -> flip' s index
Nothing -> flip' s $ length s
solve' :: Stack -> Flips -> Flips
solve' s i | all id s = i
| otherwise = solve' (flipTop s) (i + 1)
solve :: String -> Flips
solve s = solve' (parse s) 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment