aboutsummaryrefslogtreecommitdiff
path: root/2024/13-Claw_Contraption/second.hs
blob: b0af3d99a11f177cc6ca149ec0bb2a2228f140a0 (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
-- requires cabal install --lib megaparsec parser-combinators heap vector
module Main (main) where

import           Control.Monad        (void, when)
import           Data.Either
import qualified Data.Matrix          as MTX
import           Data.Ratio
import           Data.Void            (Void)
import           Text.Megaparsec
import           Text.Megaparsec.Char

type Pair = (Rational, Rational) -- X Y
type Entry = (Pair, Pair, Pair) -- ButtonA ButtonB Prize
type Input = [Entry]

type Parser = Parsec Void String

parseNumber :: Parser Rational
parseNumber = fromInteger . read <$> some digitChar

parseButton :: Parser Pair
parseButton = (,) <$> (string "Button " *> letterChar *> string ": X+" *> parseNumber)
                  <*> (string ", Y+" *> parseNumber <* eol)

parsePrize :: Parser Pair
parsePrize = (,) <$> (string "Prize: X=" *> parseNumber)
                 <*> (string ", Y=" *> parseNumber <* eol)

parseEntry :: Parser Entry
parseEntry = (,,) <$> parseButton
                  <*> parseButton
                  <*> parsePrize

parseInput' :: Parser Input
parseInput' = some (parseEntry <* optional eol) <* eof

parseInput :: String -> IO Input
parseInput filename = do
  input <- readFile filename
  case runParser parseInput' filename input of
    Left bundle  -> error $ errorBundlePretty bundle
    Right input' -> return input'

-- ax + bx = c
-- ay + by = d
compute :: Input -> Rational
compute = sum . map compute'
  where
    compute' ((ax, ay), (bx, by), (px, py)) = let (Right sol) = MTX.rref $ MTX.fromList 2 3 [ ax, bx, px + 10000000000000
                                                                                            , ay, by, py + 10000000000000 ]
                                                  x = sol MTX.! (1, 3)
                                                  y = sol MTX.! (2, 3)
                                              in if (denominator x == 1 && denominator y == 1) then 3 * x + y else 0

main :: IO ()
main = do
  input <- parseInput "input"
  print $ compute input