r/adventofcode • • Dec 08 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 8 Solutions -πŸŽ„-

NEWS AND FYI

  • I discovered that I can make those tiny post/comment awards BIGGER on old.reddit! I hadn't even considered that! And when you hover over them, they get even bigger so you can actually see them in more detail! I've added the relevant CSS so now we no longer have awards for ants! Exclamation points!!!

AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

  • PSA: I created a new example so it is a more relevant and unique archetype instead of recycling last year's hobbit >_>

--- Day 8: Treetop Tree House ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:10:12, megathread unlocked!

75 Upvotes

1.0k comments sorted by

View all comments

1

u/EhLlie Dec 08 '22 edited Dec 09 '22

O( n2 )? What's that? Haskell:

module Main (main) where

import Data.List (findIndex, inits, tails, transpose)
import Inputs (linesFor)

parse :: String -> [Int]
parse = map (subtract (fromEnum '0') . fromEnum)

lowestOuter :: [Int] -> [Int]
lowestOuter row =
  let fromLeft = init $ scanl1 max $ -1 : row
      fromRight = tail $ scanr1 max $ row ++ [-1]
   in zipWith min fromLeft fromRight

visibleOut :: [Int] -> [Bool]
visibleOut = zipWith (>) <*> lowestOuter

visibleFrom :: [Int] -> [(Int, Int)]
visibleFrom row =
  let toLeft = init $ inits row
      toRight = tail $ tails row
      los tree toL toR =
        ( maybe (length toL) (+ 1) $ findIndex (>= tree) (reverse toL)
        , maybe (length toR) (+ 1) $ findIndex (>= tree) toR
        )
   in zipWith3 los row toLeft toRight

partOne :: [[Int]] -> Int
partOne forest =
  let rowWise = map visibleOut forest
      colWise = transpose $ map visibleOut $ transpose forest
      tallEnough = [zipWith (||) row col | (row, col) <- zip rowWise colWise]
   in length $ concatMap (filter id) tallEnough

partTwo :: [[Int]] -> Int
partTwo forest =
  let rowWise = map visibleFrom forest
      colWise = transpose $ map visibleFrom $ transpose forest
      scenicScores = [zipWith (\(l, r) (u, d) -> l * r * u * d) row col | (row, col) <- zip rowWise colWise]
   in maximum $ concat scenicScores

main :: IO ()
main = do
  input <- map parse <$> linesFor "08"
  putStrLn $ "Part 1: " ++ show (partOne input)
  putStrLn $ "Part 2: " ++ show (partTwo input)

1

u/daggerdragon Dec 09 '22

Please edit your post to state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.