{-# 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)