this post was submitted on 04 Dec 2024
18 points (95.0% liked)

Advent Of Code

996 readers
4 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 4: Ceres Search

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 5 points 1 month ago

Haskell

Popular language this year :)

I got embarrassingly stuck on this one trying to be clever with list operations. Then I realized I should just use an array...

import Data.Array.Unboxed (UArray)
import Data.Array.Unboxed qualified as A
import Data.Bifunctor

readInput :: String -> UArray (Int, Int) Char
readInput s =
  let rows = lines s
      n = length rows
   in A.listArray ((1, 1), (n, n)) $ concat rows

s1 `eq` s2 = s1 == s2 || s1 == reverse s2

part1 arr = length $ filter isXmas $ concatMap lines $ A.indices arr
  where
    isXmas ps = all (A.inRange $ A.bounds arr) ps && map (arr A.!) ps `eq` "XMAS"
    lines p = [take 4 $ iterate (bimap (+ di) (+ dj)) p | (di, dj) <- [(1, 0), (0, 1), (1, 1), (1, -1)]]

part2 arr = length $ filter isXmas innerPoints
  where
    innerPoints =
      let ((i1, j1), (i2, j2)) = A.bounds arr
       in [(i, j) | i <- [i1 + 1 .. i2 - 1], j <- [j1 + 1 .. j2 - 1]]
    isXmas p = up p `eq` "MAS" && down p `eq` "MAS"
    up (i, j) = map (arr A.!) [(i + 1, j - 1), (i, j), (i - 1, j + 1)]
    down (i, j) = map (arr A.!) [(i - 1, j - 1), (i, j), (i + 1, j + 1)]

main = do
  input <- readInput <$> readFile "input04"
  print $ part1 input
  print $ part2 input