summaryrefslogtreecommitdiff
path: root/day13/day13.hs
diff options
context:
space:
mode:
authorNat Lasseter <user@4574.co.uk>2024-12-13 11:35:06 +0000
committerNat Lasseter <user@4574.co.uk>2024-12-13 11:35:06 +0000
commit5132f4aac5f77ca6ae0fd907bcc84938a9d3e4b6 (patch)
tree1108cf51f57fdf9354806fa0b22b5c3a5824d6a5 /day13/day13.hs
parent62f13b2c86440fe20b96915909dc84e86f9476f0 (diff)
[Day 13] Part 1 done.HEADmain
Diffstat (limited to 'day13/day13.hs')
-rw-r--r--day13/day13.hs57
1 files changed, 57 insertions, 0 deletions
diff --git a/day13/day13.hs b/day13/day13.hs
new file mode 100644
index 0000000..4ca7b65
--- /dev/null
+++ b/day13/day13.hs
@@ -0,0 +1,57 @@
+import Data.List
+import Data.List.Split
+import Data.Maybe
+import Text.Read
+
+type Cost = Int
+type Vec = (Int, Int)
+type Machine = (Vec, Vec, Vec)
+
+mul :: Int -> Vec -> Vec
+mul s (x, y) = (s*x, s*y)
+add :: Vec -> Vec -> Vec
+add (x, y) (z, w) = (x+z, y+w)
+
+consume1 :: [String] -> Machine
+consume1 (a:b:p:_) =
+ (parseVec "+," a, parseVec "+," b, parseVec "=," p)
+ where
+ toVec [x, y] = (x,y)
+ parseVec spl str = toVec $ catMaybes $ map (readMaybe::String->Maybe Int) $ splitOneOf spl str
+
+consume :: String -> [Machine]
+consume file =
+ map consume1 macs
+ where
+ macs = chunksOf 4 $ lines file
+
+winnable :: Machine -> [Vec]
+winnable (a, b, p) =
+ filter winner opts
+ where
+ winner (x, y) = (x `mul` a) `add` (y `mul` b) == p
+ opts = [(na, nb) | na <- [0..100], nb <- [0..100]]
+
+cost :: Vec -> Cost
+cost (a, b) = 3*a + b
+
+cheapest1 :: Cost -> [Vec] -> Cost
+cheapest1 cst [] = cst
+cheapest1 cst (h:t)
+ | hcst < cst = cheapest1 hcst t
+ | otherwise = cheapest1 cst t
+ where
+ hcst = cost h
+
+cheapest :: [Vec] -> Cost
+cheapest [] = 0
+cheapest v = cheapest1 (maxBound :: Int) v
+
+part1 :: [Machine] -> Cost
+part1 = sum . map cheapest . map winnable
+
+main = do
+ file <- readFile "day13.input"
+ let machines = consume file
+ putStrLn ("Part 1: " ++ (show $ part1 machines))
+ --putStrLn ("Part 2: " ++ (show $ part2 machines))