aoc2021/Day6_1.hs

30 lines
948 B
Haskell

module Day6_1 where
import System.IO (openFile, IOMode (ReadMode), hClose, hGetContents)
import Data.Text (splitOn, unpack, pack)
import Prelude hiding (splitAt)
import Data.List (group, sort)
import Data.Map.Strict (toList, fromListWith)
splitAt :: String -> String -> [String]
splitAt delimiter str = map unpack $ splitOn (pack delimiter) $ pack str
count :: [Int] -> [(Int, Int)]
count fish = map (\x -> (head x, length x)) $ group $ sort fish
grow :: (Int, Int) -> [(Int, Int)]
grow fish
| fst fish > 0 = [(fst fish - 1, snd fish)]
| otherwise = [(6, snd fish), (8, snd fish)]
sumFishes :: [(Int, Int)] -> [(Int, Int)]
sumFishes = toList . fromListWith (+)
main :: IO ()
main = do
input <- openFile "inputs/6.txt" ReadMode
contents <- hGetContents input
let fishies = map read $ splitAt "," contents :: [Int]
print . sum . map snd . (!! 256) . iterate (sumFishes . concatMap grow) $ count fishies
hClose input