AoC 2022 D3: Rucksack Reorganization

Haskell | Problem statement | Source code | Tags: Data structures

← Previous Back to AoC Index Next →

Part 1

I convert the two halves of each string into sets and find the intersection.

solve1 :: [Text] -> IO ()
solve1 input = do
let compartments = map (\line -> T.splitAt (T.length line `div` 2) line) input
print $ sumMap (\(a, b) -> commonPriority (textToSet a) (textToSet b)) compartments

textToSet :: Text -> Set Char
textToSet = Set.fromList . T.unpack

commonPriority :: Set Char -> Set Char -> Int
commonPriority a b = priority $ Set.elemAt 0 $ Set.intersection a b
hs

Part 2

I made a little utility called chunksOf to split the input into chunks of 3.

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = take n xs : chunksOf n (drop n xs)
hs

Now I can find the common item in each chunk of 3 rucksacks the same way as in part 1.

solve2 :: [Text] -> IO ()
solve2 input = do
let groups = map (map textToSet) $ chunksOf 3 input
print $ sumMap (\[a, b, c] -> commonPriority a $ Set.intersection b c) groups
hs

← Previous Back to AoC Index Next →