r/haskell • • 1d ago

AoC Advent of Code 2026 Day 4

https://adventofcode.com/2026/day/4
10 Upvotes

5 comments sorted by

2

u/Atijohn 22h ago edited 22h ago
import Control.Monad
import Data.Bifunctor
import Data.Function
import Data.Functor
import Data.List
import Data.Maybe

main = print
     . join bimap (sum
     . map
       (length
      . head
      . head
      . dropWhile (not
                 . isJust
                 . (foldl' (\z x -> z >>= sequence . zipWith fit x)
                <$> Just . head
                <*> tail))
      . (zipWith chunk . enumFromTo 1 . length <*> repeat)))
     . ((,) <$> lines <*> pure . filter (/='\n'))
   =<< getContents
  where chunk _ [] = []
        chunk n xs = take n xs : chunk n (drop n xs)
        fit '?' c = Just c
        fit c '?' = Just c
        fit a b = guard (a == b) $> a

(this one had way too many edge cases, so I just left it at the point where it worked for my input)

1

u/AustinVelonaut 22h ago

I originally wrote this by breaking up the code into fixed sized chunks, transposing the chunk list, then checking that each resulting row string had all "equal" colors (either same color or '?'). Then I realized that I could just step through a fixed Vector by increasing strides, checking that each offset for each stride had the same character, which was much faster. I used the "early-out foldl from foldr" trick to early-out on a mismatch. A bit more "imperative" than the first solution, though.

import qualified Data.Vector as V
import Data.List (find)
import Data.Maybe (fromJust)

-- check for a color collision on all strides from 1 .. len, returning the first
-- stride that has no collisions for any offset [0 .. stride - 1]
minInstructions :: String -> Int
minInstructions s
    = fromJust $ find noCollisions [1 .. len]
      where
        code = V.fromList s
        len  = V.length code

        noCollisions stride = all (match stride) [0 .. stride - 1]
        
        -- early-out foldl from foldr
        match stride offset
            = foldr check (const True) [offset, offset + stride .. len - 1] '?'
              where
                check i k t
                    = (t == '?' || v == '?' || t == v) && k t'
                      where
                        v  = code V.! i
                        t' = if v == '?' then  t else v

main :: IO ()
main
    = readFile "../inputs/day04.txt" >>= (go . lines)
      where
        go codes
            = part1 >> part2
              where
                part1 = putStrLn . show . sum . map minInstructions $ codes
                part2 = putStrLn . show . minInstructions . concat $ codes

1

u/Apterygiformes 17h ago
import qualified Data.Set as S
import Data.List
import Control.Monad (guard) 

pad :: String -> Int -> String
pad s n  = s ++ (take (n - length s) (repeat '?'))

partitions :: String -> Int -> [String]
partitions s n  | length s > n = (take n s) : partitions (drop n s) n
                | otherwise = [pad s n]

valid :: [String] -> Bool
valid [] = True
valid (p:ps) | S.size s == 1 = True && valid ps
             | S.size s == 2 && S.member '?' s = True && valid ps
             | otherwise = False
        where
               s = S.fromList p

solutions :: String -> [String]
solutions s = do
        n <- [1..length s - 1]
        let ps = partitions s n
        guard $ valid $ transpose ps
        ps
  
main :: IO ()
main = do
    input <- readFile "input.txt"
    let barcodes = length $ head $ solutions $ concat $ lines input
    putStrLn $ show barcodes
    return ()

1

u/tom_da_boom 15h ago
module Main where

main :: IO ()
main = do
    fs <- readFile "..."

    let codes   = lines fs
    let bigCode = filter (/= '\n') fs

    putStr "Task 1: "
    print $ sum $ map minCode codes

    putStr "Task 2: "
    print $ minCode bigCode

type Code = [Char]
type Idxs = [(Char, Int)]

toIndices :: Code -> Idxs
toIndices cs = [ (c, i) | (c, i) <- zip cs [0..], c /= '?' ]

validLength :: Int -> Idxs -> Bool
validLength _ []         = True
validLength l ((c,i):is) = 
    and [ mod i l /= mod j l | (d, j) <- is, d /= c ]  
    && validLength l is 

minCode :: Code -> Int
minCode cs = go 1 where 
    is = toIndices cs
    go l
        | validLength l is = l
        | otherwise        = go (l+1)

1

u/wyxx_jellyfish 14h ago edited 14h ago
module Main where

forced :: Int -> String -> [(Int, Char)]
forced n =  map (\(i, c) -> (i `mod` n, c)) . filter ((/=) '?' . snd) . zip [0 ..]

isPossible :: [(Int, Char)] -> Bool
isPossible xs = all (\(i, c) -> not (any (\(i', c') -> c' /= c && i' == i) xs)) xs

solve :: String -> Int
solve xs = minimum [n | n <- [1 .. length ys], isPossible $ forced n ys]
 where
  ys = concat $ lines xs

main :: IO ()
main = do
  input <- readFile "../inputs/day4.txt"
  print $ solve input