blob: 5c589e7727b4350817e23db9796ec26cc9b3599e (
plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
import Data.List
import Data.List.Split
type Rule = [Int]
type Update = [Int]
relevant :: Update -> Rule -> Bool
relevant upd (b:a:[]) = (b `elem` upd) && (a `elem` upd)
abides :: Update -> Rule -> Bool
abides [] _ = False
abides (h:t) r@(a:[])
| h == a = True
| otherwise = abides t r
abides (h:t) r@(b:a:[])
| h == b = abides t [a]
| otherwise = abides t r
middle :: [Int] -> Int
middle arr = arr !! (length arr `div` 2)
valid :: [Rule] -> Update -> Bool
valid rules update =
all (abides update) $ filter (relevant update) rules
apply :: [Rule] -> Int -> Int -> Ordering
apply rules a b
| [a,b] `elem` rules = LT
| [b,a] `elem` rules = GT
| otherwise = EQ
part11 :: Int -> [Rule] -> [Update] -> Int
part11 acc _ [] = acc
part11 acc rules (h:t)
| valid rules h = part11 (acc + (middle h)) rules t
| otherwise = part11 acc rules t
part1 :: [Rule] -> [Update] -> Int
part1 rules updates =
part11 0 rules updates
part21 :: Int -> [Rule] -> [Update] -> Int
part21 acc _ [] = acc
part21 acc rules (h:t)
| valid rules h = part21 acc rules t
| otherwise =
let rrules = filter (relevant h) rules
sfun = apply rrules
inc = middle $ sortBy (sfun) h in
part21 (acc + inc) rules t
part2 :: [Rule] -> [Update] -> Int
part2 rules updates =
part21 0 rules updates
main = do
file <- readFile "day05.input"
let lns = lines file
rulesin:updatesin:[] = splitOn [""] lns
rules = map (map (read::String->Int)) $ map (splitOn "|") rulesin
updates = map (map (read::String -> Int)) $ map (splitOn ",") updatesin
putStrLn ("Part 1: " ++ (show $ part1 rules updates))
putStrLn ("Part 2: " ++ (show $ part2 rules updates))
|