···
3
+
import Data.Ratio ((%), Ratio)
5
+
import Data.Maybe (catMaybes)
6
+
import Data.Ord (comparing)
7
+
import Data.List (sortBy)
8
+
import qualified Data.Map as Map
9
+
import Data.Map (Map)
13
+
type Display = [Int]
14
+
type Machine = (Button, [Button], [Int])
16
+
parse :: String -> [Machine]
17
+
parse = map parseLine . lines
18
+
where parseDisplay :: String -> [Int]
19
+
parseDisplay s = [i | (i,c) <- zip [0..] (init (tail s)), c == '#']
21
+
parseInts :: String -> [Int]
22
+
parseInts s = map read $ split ',' $ (init (tail s))
28
+
in (parseDisplay disp, map parseInts (init (tail w)), parseInts jolt)
30
+
xor :: [Int] -> [Int] -> [Int]
33
+
xor (a:as) (b:bs) | a < b = (a : xor as (b:bs))
34
+
xor (a:as) (b:bs) | a == b = xor as bs
35
+
xor (a:as) (b:bs) | a > b = (b : xor (a:as) bs)
37
+
minimumMaybe :: [Maybe Int] -> Maybe Int
39
+
case catMaybes ns of
41
+
ns' -> Just $ minimum ns'
43
+
solveMachine :: Machine -> Maybe Int
44
+
solveMachine ([],[],_) = Just 0
45
+
solveMachine (_,[],_) = Nothing
46
+
solveMachine (goal, (b:bs), jolt) =
47
+
minimumMaybe [solveMachine (goal, bs, jolt),
48
+
(+ 1) <$> solveMachine (xor goal b, bs, jolt)]
part1 :: String -> String
4
-
part1 _ = "Day 10 part 1"
52
+
let machines = parse input
53
+
solutions = map solveMachine machines
54
+
in case sequence solutions of
55
+
Just ss -> show $ sum ss
58
+
buttonToRepeat :: Int -> Button -> [Int]
59
+
buttonToRepeat i button = go 0 button
60
+
where go n [] = repeat 0
65
+
(0 : go (n+1) (b:bs))
67
+
gaussJordan :: Map (Int,Int) (Ratio Int) -> Map Int (Ratio Int) -> (Map (Int,Int) (Ratio Int), Map Int (Ratio Int), Int)
68
+
gaussJordan m g = error "GJ"
70
+
solveMachine2 :: [Button] -> [Int] -> Maybe Int
71
+
solveMachine2 buttons goal =
72
+
let mat = Map.fromList [((i,j),1 % 1) | (i,b) <- zip [0..] buttons, j <- b]
73
+
g = Map.fromList $ zip [0..] (map (% 1) goal)
74
+
(mat', g', rank) = gaussJordan mat g
part2 :: String -> String
7
-
part2 _ = "Day 10 part 2"
79
+
let machines = parse input
80
+
solutions = map (\(_,b,g) -> solveMachine2 b g) machines
81
+
in case sequence solutions of
82
+
Just ss -> show $ sum ss