Skip to content

Instantly share code, notes, and snippets.

@MarisaKirisame
Last active March 22, 2023 04:35
Show Gist options
  • Save MarisaKirisame/e7d08ce728780c7ce8e3076ed907dfe2 to your computer and use it in GitHub Desktop.
Save MarisaKirisame/e7d08ce728780c7ce8e3076ed907dfe2 to your computer and use it in GitHub Desktop.
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