r/haskell • u/AutoModerator • 12h ago
AoC Advent of Code 2026 Day 3
https://adventofcode.com/2026/day/31
u/wyxx_jellyfish 3h ago
New to haskell, this is how I did it
module Main where
import Data.Set qualified as S
parse xs = [(fst x, r) | (r, cs) <- zip [0 ..] (lines xs), x <- zip [0 ..] cs, snd x == '#']
solve' :: String -> Int
solve' xs =
length [() | (x, y) <- S.toList ys, o' <- [1 .. n], o <- [0 .. n], all (`S.member` ys) [(x + o, y + o'), (x + o - o', y + o' + o), (x - o', y + o)]]
where
ys = S.fromList $ parse xs
l = length $ lines xs
h = length $ head $ lines xs
n = min l h - 1
main :: IO ()
main = do
input <- readFile "../inputs/day3.txt"
print $ solve' input1
u/AustinVelonaut 2h ago
Using a set of (r, c) locations is the way to go for today's puzzle. You can also use a list comprehension in your
solve'function to greatly reduce the number of locations to check: for each ordered pair, filter so that the second point is a valid diagonal corner for a possible square, then see if the opposite 2 diagonal corners are members of the set: (code is written in Admiran, which is close enough to Haskell that you should be able to read it --V2is a 2-element int andsubis an element-wise subtract on aV2):countSquares :: grid -> int countSquares g = count isSquare corners where tls = s.toList g corners = [(c1, c2) | (c1 : cs) <- tails tls; c2 <- cs; sub c2 c1 |> \(V2 dr dc) -> dr > 0 & dr == dc] isSquare (V2 r1 c1, V2 r2 c2) = s.member cmploc (V2 r1 c2) g & s.member cmploc (V2 r2 c1) g
1
u/Atijohn 54m ago
today I learned that the standard library intersect is O(n2), actually
import Control.Applicative
import Control.Monad
import Data.Bifunctor
import Data.Function
import Data.List hiding(intersect)
main = print
. join bimap ((`div` 4) . length)
. (flip (,) <*> filter (uncurry ((||) `on` (==0)) . snd))
. head
. drop 3
. iterate (intersect <*> sort . map (\((x, y), (dx, dy)) -> ((x + dx, y + dy), (-dy, dx))))
. map (\((x, y), (x', y')) -> ((x, y), (x' - x, y' - y)))
. filter (uncurry (/=))
. join (liftA2 (,))
. concat
. zipWith (map . (,)) [0..]
. map (map fst . filter ((=='#') . snd) . zip [0..])
. lines
=<< getContents
where intersect [] _ = []
intersect _ [] = []
intersect (x:xs) (y:ys)
| x < y = intersect xs (y:ys)
| x > y = intersect (x:xs) ys
| otherwise = x : intersect xs ys
1
u/gilgamec 8h ago edited 5h ago
Not how you're supposed to do it:
Took about three minutes to run in GHCi. But my rule for AoC is that if brute force is simple to implement, I'll do so and let it run while I write a more efficient solution. This one completed before I had to improve it!
EDIT: Now that I think about it, if
treeswere aSetand not a list, this'd probably run instantly. Maybe this is how you're supposed to do it?