Browse Source

Day 13

mistress
Agatha Lovelace 1 month ago
parent
commit
018bae2654
  1. 29
      Day13.hs
  2. 47
      Day13_1.hs

29
Day13.hs

@ -0,0 +1,29 @@
module Day13 where
import System.IO (openFile)
import Data.Text (unpack, splitOn, pack)
import Prelude hiding (splitAt)
import Data.Char (digitToInt)
import Data.List (nub)
splitAt :: String -> String -> [String]
splitAt delimiter str = map unpack $ splitOn (pack delimiter) $ pack str
fold :: (Int, Int) -> String -> (Int, Int)
fold (x, y) str
| head str == 'x' = (fold' x, y)
| head str == 'y' = (x, fold' y)
where coord = read . last $ splitAt "=" str
fold' num
| num > coord = coord - (num - coord)
| otherwise = num
main :: IO ()
main = do
input <- readFile "inputs/13.txt"
let (coords', folds') = (\[a,b] -> (lines a, lines b)) $ splitAt "\n\n" input
--
let coords = (\[a,b] -> (read a, read b) :: (Int, Int)) <$> map (splitAt ",") coords'
folds = map (last . splitAt " ") folds'
print . length . nub $ [fold pos (head folds) | pos <- coords ]

47
Day13_1.hs

@ -0,0 +1,47 @@
module Day13_1 where
import System.IO (openFile)
import Data.Text (unpack, splitOn, pack)
import Prelude hiding (splitAt)
import Data.Char (digitToInt)
import Data.List (nub)
splitAt :: String -> String -> [String]
splitAt delimiter str = map unpack $ splitOn (pack delimiter) $ pack str
insert :: Int -> Char -> [Char] -> [Char]
insert 0 y xs = xs
insert n y [] = []
insert n y xs
| length xs < n = xs
| otherwise = take n xs ++ [y] ++ insert n y (drop n xs)
fold :: String -> (Int, Int) -> (Int, Int)
fold str (x, y)
| head str == 'x' = (fold' x, y)
| head str == 'y' = (x, fold' y)
where coord = read . last $ splitAt "=" str
fold' num
| num > coord = coord - (num - coord)
| otherwise = num
main :: IO ()
main = do
input <- readFile "inputs/13.txt"
let (coords', folds') = (\[a,b] -> (lines a, lines b)) $ splitAt "\n\n" input
--
let coords = (\[a,b] -> (read a, read b) :: (Int, Int)) <$> map (splitAt ",") coords'
folds = map (last . splitAt " ") folds'
let result = nub $ foldl (\acc x -> map (fold x) acc) coords folds
let width = maximum $ fst <$> result
height = maximum $ snd <$> result
field = (,) <$> [0..width] <*> [0..height]
let display x
| x `elem` result = '#'
| otherwise = '.'
-- the text is actually vertical, because of course it is
in putStrLn $ insert (height+1) '\n' $ map display field
Loading…
Cancel
Save