Skip to content

Instantly share code, notes, and snippets.

@mhitza
Last active December 8, 2022 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhitza/736a437ce1d2a8802bc562bdb8893fb0 to your computer and use it in GitHub Desktop.
Save mhitza/736a437ce1d2a8802bc562bdb8893fb0 to your computer and use it in GitHub Desktop.
Day 8 advent of code 2022
{-# LANGUAGE BlockArguments, Strict #-}
import Control.Monad.State
import Data.List
import Data.Char
import Data.Bifunctor
takeUntilIncluding p [] = []
takeUntilIncluding p (x:xs)
| p x == True = x : takeUntilIncluding p xs
| otherwise = [x]
focus list position project =
let (before, (tree:after)) = splitAt position (list !! project)
in (reverse before, tree, after)
nextElementWith (rows,cols) f =
let endsRow v = v == length (head rows) - 1
endsCol v = v == length rows - 1
in gets fst >>= \(row,col) ->
case (endsRow (row + 1), endsCol (col + 1)) of
(True, True) -> pure ()
(True, False) -> modify (first (const (1, col + 1))) >> f
_ -> modify (first (const (row + 1, col))) >> f
part1 grid@(rows,cols) = ((+) implicitlyVisible) . snd $ execState traverseGrid ((1,1),0)
where
implicitlyVisible = (((length rows) - 1) * 2) + ((length cols) - 1) * 2
check (before,tree,after) = let vb = (any (>= tree) before)
va = (any (>= tree) after)
in vb && va
traverseGrid = gets fst >>= \(row,col) -> do
unless (check (focus rows col row) && check (focus cols row col))
do modify (second (+1))
grid `nextElementWith` traverseGrid
part2 grid@(rows,cols) = snd $ execState traverseGrid ((1,1),0)
where
check (before, tree, after) = let b = length $ takeUntilIncluding (tree >) before
a = length $ takeUntilIncluding (tree >) after
in (b,a)
traverseGrid = gets fst >>= \(row,col) -> do
let (rb,ra) = check (focus rows col row)
let (cb,ca) = check (focus cols row col)
modify (second (max (rb * ra * cb * ca)))
grid `nextElementWith` traverseGrid
main = do
rows <- (map (map digitToInt) . lines) <$> readFile "/tmp/input.txt"
let grid = (rows, transpose rows)
print $ part1 grid
print $ part2 grid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment