Advent of Code solutions https://adventofcode.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.3KB

  1. import Data.List (sort)
  2. main :: IO()
  3. main = do
  4. input <- readFile "input"
  5. print . mySeat . map seatId . map seat . lines $ input
  6. mySeat :: [Int] -> Int
  7. mySeat = findGap . sort
  8. findGap :: [Int] -> Int
  9. findGap (a:b:rest)
  10. | (b - a) > 1 = b - 1
  11. | otherwise = findGap $ b:rest
  12. seatId :: (Int, Int) -> Int
  13. seatId (row, col) = (row * 8) + col
  14. seat :: String -> (Int, Int)
  15. seat line = (row fst, col snd) where (fst, snd) = splitAt 7 line
  16. row :: String -> Int
  17. row = partition 'F' 'B' 0 127
  18. col :: String -> Int
  19. col = partition 'L' 'R' 0 7
  20. -- Perform binary space partition. The first two arguments are the characters
  21. -- which indicate that the lower or upper part of the space will be used
  22. -- respectively. The second two are the starting upper and lower bounds of the
  23. -- search space. The last is the instructions string.
  24. partition :: Char -> Char -> Int -> Int -> String -> Int
  25. partition _ _ min _ [] = min
  26. partition lowerC upperC min max str@(c:cs)
  27. | c == upperC = partition' (mid min max) max cs
  28. | c == lowerC = partition' min (mid min max) cs
  29. | otherwise = partition' min max cs
  30. where partition' = partition lowerC upperC
  31. -- Find the midpoint of two integers, e.g. the midpoint of 0 and 7 is 4
  32. mid :: Int -> Int -> Int
  33. mid a b = div (a + b + 1) 2