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

import Data.Foldable (toList)
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'

bfs :: (Ord a, Foldable t) => (a -> t a) -> Set a -> Set a
bfs f = go mempty
  where
    go seen front | Set.null front = seen
    go seen front =
      let seen' = seen <> front
          news = Set.fromList [y | x <- Set.toList front, y <- toList (f x)] Set.\\ seen'
      in go 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 $ bfs (\n -> [press n b | b <- btns]) (Set.singleton 0)