-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.hs
47 lines (41 loc) · 1.1 KB
/
run.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
import qualified Data.ByteString.Lazy as BL
import Data.List (sort)
import Data.List.Split (splitOn)
import Data.Text.Encoding (decodeUtf8)
import Data.Text.Read (decimal)
largest3 :: [Int] -> [Int]
largest3 = \case a:b:c:rest ->
let [a',b',c'] = sort [a,b,c]
in go a' b' c' rest
xs -> sort xs
where -- a <= b <= c
go a b c [] = [a,b,c]
go !a !b !c (!x:xs)
| x >= c = go b c x xs
| x >= b = go b x c xs
| x >= a = go x b c xs
| otherwise = go a b c xs
parse :: BL.ByteString -> Int
parse =
(\case (Right (x, _)) -> x)
. decimal
. decodeUtf8
. BL.toStrict
parseAll :: BL.ByteString -> [[Int]]
parseAll =
map (map parse)
. filter (not . null)
. splitOn [BL.empty]
. BL.split 0x0a
main :: IO ()
main =
main' "input.txt"
process :: BL.ByteString -> [Int]
process = largest3 . map sum . parseAll
main' :: FilePath -> IO ()
main' file = do
[x1, x2, x3] <- process <$> BL.readFile file
print $ x3
print $ x1 + x2 + x3