summaryrefslogtreecommitdiff
path: root/2026/5.hs
blob: c6b5f4914797b9f50282f66f4d26255f87c99cea (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
{-# OPTIONS -Wno-x-partial #-}
module Main where

import Data.List (foldl')
import Data.Set qualified as Set
import Data.Set (Set)
import Numeric (showOct)


cartprod :: Int -> [a] -> [[a]]
cartprod 0 _ = [[]]
cartprod n l = [x : xs | xs <- cartprod (n - 1) l, x <- l]

data Btn = Type Int | Mul Int | Div Int | Sub Char Char | Oct | Bksp
  deriving (Show, Eq, Ord)

parseBtn :: String -> Btn
parseBtn "oct" = Oct
parseBtn "bksp" = Bksp
parseBtn ('*':s) = Mul (read s)
parseBtn ('/':s) = Div (read s)
parseBtn [a,'-','>',b] = Sub a b
parseBtn s = Type (read s)

press :: Int -> Btn -> Int
press n btn =
  let n' = case btn of
             Type k -> 10 * n + k
             Mul k -> n * k
             Div k -> n `quot` k
             Sub a b -> read (map (\c -> if c == a then b else c) (show n))
             Oct -> read (showOct n "")
             Bksp -> n `quot` 10
  in if n' >= 10000 then n else n'

search :: [Btn] -> Set Int -> Set Int -> Set Int
search _    seen front | Set.null front = seen
search btns seen front =
  let seen' = seen <> front
      news = Set.fromList [press n b | n <- Set.toList front, b <- btns] Set.\\ seen'
  in search btns seen' news

main :: IO ()
main = do
  btns <- map (parseBtn . init . tail) . words <$> getContents
  print . sum . Set.toList $ Set.fromList . map (foldl' press 0) $ cartprod 3 btns
  print . sum . Set.toList $ search btns mempty (Set.singleton 0)