Files

89 lines
2.2 KiB
Haskell
Raw Permalink Normal View History

2024-12-14 22:34:07 +01:00
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
2024-12-20 18:00:43 +01:00
module Day14
( day14_1,
day14_2,
)
where
2024-12-14 19:15:28 +01:00
2024-12-14 17:04:58 +01:00
import Data.Char (isDigit)
2024-12-20 18:00:43 +01:00
import Data.List (nub)
2024-12-14 17:04:58 +01:00
import Data.List.Split (splitOn)
type Position = (Int, Int)
2024-12-15 10:31:53 +01:00
2024-12-14 17:04:58 +01:00
type Velocity = (Int, Int)
2024-12-15 10:31:53 +01:00
2024-12-14 17:04:58 +01:00
type Robot = (Position, Velocity)
readRobot :: String -> Robot
2024-12-15 10:31:53 +01:00
readRobot s =
let [ps, vs] = splitOn " " s
[px, py] = map read . splitOn "," $ filter (\x -> isDigit x || x == ',' || x == '-') ps
[vx, vy] = map read . splitOn "," $ filter (\x -> isDigit x || x == ',' || x == '-') vs
in ((px, py), (vx, vy))
2024-12-14 17:04:58 +01:00
moveRobot :: Int -> Robot -> Robot
moveRobot 0 r = r
2024-12-15 10:31:53 +01:00
moveRobot n r =
let (px, py) = fst r
(vx, vy) = snd r
in moveRobot (n - 1) (((px + vx) `mod` 101, (py + vy) `mod` 103), (vx, vy))
2024-12-14 17:04:58 +01:00
2024-12-20 18:00:43 +01:00
moveRobot' :: Robot -> Robot
moveRobot' r =
let (px, py) = fst r
(vx, vy) = snd r
in (((px + vx) `mod` 101, (py + vy) `mod` 103), (vx, vy))
2024-12-14 17:04:58 +01:00
quadrant :: Robot -> Int
quadrant r
2024-12-15 10:31:53 +01:00
| fst p `elem` [0 .. 49]
&& snd p `elem` [0 .. 50] =
0
| fst p `elem` [51 .. 100]
&& snd p `elem` [0 .. 50] =
1
| fst p `elem` [0 .. 49]
&& snd p `elem` [52 .. 102] =
2
| fst p `elem` [51 .. 100]
&& snd p `elem` [52 .. 102] =
3
| otherwise = -1
where
p = fst r
2024-12-14 17:04:58 +01:00
2024-12-20 18:00:43 +01:00
findChristmasTree :: Int -> [Robot] -> Int
findChristmasTree n rs =
let rs' = map moveRobot' rs
positions = map fst rs'
in if positions == nub positions
then n
else findChristmasTree (n + 1) rs'
2024-12-21 20:03:24 +01:00
parseInput :: IO [Robot]
parseInput = do
2024-12-15 10:31:53 +01:00
contents <- lines <$> readFile "input/day14.txt"
let robots = map readRobot contents
2024-12-21 20:03:24 +01:00
return robots
day14_1 :: IO ()
day14_1 = do
robots <- parseInput
let robots' = map (moveRobot 100) robots
2024-12-15 10:31:53 +01:00
firstQ = length $ filter (\r -> quadrant r == 0) robots'
secondQ = length $ filter (\r -> quadrant r == 1) robots'
thirdQ = length $ filter (\r -> quadrant r == 2) robots'
fourthQ = length $ filter (\r -> quadrant r == 3) robots'
putStrLn $
"Day 14, Puzzle 1 solution: "
++ show (firstQ * secondQ * thirdQ * fourthQ)
2024-12-20 18:00:43 +01:00
day14_2 :: IO ()
day14_2 = do
2024-12-21 20:03:24 +01:00
robots <- parseInput
2024-12-20 18:00:43 +01:00
putStrLn $
"Day 14, Puzzle 2 solution: "
++ show (findChristmasTree 1 robots)