Last active
March 22, 2023 04:35
-
-
Save MarisaKirisame/e7d08ce728780c7ce8e3076ed907dfe2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List | |
data Op = Add | Mult | Sub | |
select :: [x] -> [(x, [x])] | |
select [] = [] | |
select (a : b) = (a, b) : (do | |
(c, d) <- select b | |
return $ (c, a : d)) | |
pBinOp :: String -> String -> String -> String | |
pBinOp l op r = "(" ++ l ++ " " ++ op ++ " " ++ r ++ ")" | |
interp :: Op -> (Int, String) -> (Int, String) -> (Int, String) | |
interp Add (a, aname) (b, bname) = (a + b, pBinOp aname "+" bname) | |
interp Mult (a, aname) (b, bname) = (a * b, pBinOp aname "*" bname) | |
interp Sub (a, aname) (b, bname) = (a - b, pBinOp aname "-" bname) | |
merge :: [(Int, String)] -> [(Int, String)] | |
merge [] = undefined | |
merge [x] = [x] | |
merge x = do | |
(l, x') <- select x | |
op <- [Add, Mult, Sub] | |
(r, x'') <- select x' | |
merge ((interp op l r) : x'') | |
twenty_four_with_dup :: Int -> Int -> Int -> Int -> [String] | |
twenty_four_with_dup a_ b_ c_ d_ = do | |
res <- merge $ map (\x -> (x, show x)) [a_, b_, c_, d_] | |
if (fst res == 24) then [snd res] else [] | |
rmdups :: (Ord a) => [a] -> [a] | |
rmdups = map head . group . sort | |
twenty_four :: Int -> Int -> Int -> Int -> [String] | |
twenty_four a b c d = rmdups $ twenty_four_with_dup a b c d | |
main = print $ twenty_four 3 3 2 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment