09/12/23 18:35:26
>>35 Haskellで
import Control.Monad.State
import qualified Data.Set as S
import qualified Data.Map as M
type Proc = StateT (M.Map Char Int, S.Set Int) []
solve :: [String]
solve = flip evalStateT (M.empty, S.fromList [0..9]) $ do
osaka <- int "osaka"
kyoto <- int "kyoto"
tokyo <- int "tokyo"
guard $ osaka + kyoto == tokyo
return $ show osaka ++ " + " ++ show kyoto ++ " = " ++ show tokyo
main = putStr $ unlines solve
int :: String -> Proc Int
int xs = do
(d:ds) <- mapM digit xs
guard $ d /= 0
return $ foldl (\n c -> n * 10 + c) 0 (d:ds)
digit :: Char -> Proc Int
digit c = do
(m, s) <- get
case M.lookup c m of
Just d -> return d
Nothing -> do
d <- lift $ S.toList s
put (M.insert c d m, S.delete d s)
return d