Skip to content

Instantly share code, notes, and snippets.

@zavodnoyapl1992
Created December 23, 2021 10:17
Show Gist options
  • Save zavodnoyapl1992/c9113848737972531e3776be70631fb3 to your computer and use it in GitHub Desktop.
Save zavodnoyapl1992/c9113848737972531e3776be70631fb3 to your computer and use it in GitHub Desktop.
import Data.List.Split(splitOn)
isWin :: [[Maybe Integer]] -> Bool
isWin xs = any isWin1 [xs, revertMatrix xs []] where
revertMatrix [] newMat = newMat
revertMatrix xs newMat = revertMatrix (filter (\y -> length y > 0) (map tail xs)) (newMat ++ [map head xs])
isWin1 [] = False
isWin1 (x:xs) | complete x = True
| otherwise = isWin1 xs
where
complete [] = True
complete ((Nothing):xs) = complete xs
complete ((Just _):_) = False
getSum :: [[Maybe Integer]] -> Integer
getSum [] = 0
getSum (x:xs) = getS x + getSum xs where
getS [] = 0
getS ((Nothing):xs) = getS xs
getS ((Just i):xs) = i + getS xs
getCard x xs = (getCardRow x) : xs
getCardRow x = map (\y -> Just (read y :: Integer)) (words x)
parseCards [] [] cards = cards
parseCards [] card cards = card:cards
parseCards ("":xs) [] cards = parseCards xs [] cards
parseCards ("":xs) card cards = parseCards xs [] (card:cards)
parseCards (current:xs) card cards = parseCards xs (getCard current card) cards
addNumber :: Integer -> [[Maybe Integer]] -> [[Maybe Integer]]
addNumber _ [] = []
addNumber n (x:xs) = (checkerNumber x n):(addNumber n xs) where
checkerNumber [] _ = []
checkerNumber (a@(Just x):xs) n | x == n = Nothing:(checkerNumber xs n)
| otherwise = a:(checkerNumber xs n)
checkerNumber (x:xs) n = x:(checkerNumber xs n)
play1 _ [] = Nothing
play1 xs (n:nx) | any isWin (map (addNumber n) xs) = getResult (map (addNumber n) xs) n
| otherwise = play1 (map (addNumber n) xs) nx
where
getResult (x:xs) n | isWin x = Just (n * (getSum x))
| otherwise = getResult xs n
play2 [x] (n:_) = Just (n * (getSum (addNumber n x)))
play2 xs (n:nx) = play2 (filter (\y -> not $ isWin y) (map (addNumber n) xs)) nx
part1 (x:xs) = play1 (parseCards xs [] []) (getNums x)
part2 (x:xs) = play2 (parseCards xs [] []) (getNums x)
getNums x = map (\y -> read y :: Integer) (splitOn "," x)
solve :: String -> IO ()
solve filename = do
c <- readFile filename
print $ part1 (lines c)
print $ part2 (lines c)
main = solve "input.txt"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment