Skip to content

Instantly share code, notes, and snippets.

@newjam
Created March 20, 2014 05:00
Show Gist options
  • Save newjam/9657561 to your computer and use it in GitHub Desktop.
Save newjam/9657561 to your computer and use it in GitHub Desktop.
Find a simple arithmetic expression that evaluates to 24 using the numbers 1, 3, 4, 6 exactly once.
import Data.Ratio
import qualified Data.Set as S
data Op = Add | Sub | Mul | Div
deriving Eq
data Exp a = Bin Op (Exp a) (Exp a)
| Num a
deriving Eq
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
instance Show a => Show (Exp a) where
show (Num x) = show x
show (Bin op e1 e2) = "(" ++ show e1 ++ show op ++ show e2 ++ ")" where
numbers = [1.0,3.0,4.0,6.0]
ops = [Add, Sub, Mul, Div]
value (Num x) = x
value (Bin op e1 e2) = (value e1) `op'` (value e2) where
op' = case op of
Add -> (+)
Sub -> (-)
Mul -> (*)
Div -> (/)
base (Num x) = S.singleton x
base (Bin _ e1 e2) = base e1 `S.union` base e2
different e1 e2 = S.size (base e1 `S.intersection` base e2) == 0
size (Num _) = 1
size (Bin _ e1 e2) = size e1 + size e2
generate es = es ++ [Bin op e1 e2 | e1 <- es, e2 <- es, op <- ops, e1 `differen
t` e2]
allExpressions = generate . generate . generate . map Num $ numbers
allValidExpressions = filter (\e -> size e == 4) allExpressions
solutions = filter (\e -> value e == 24.0) allValidExpressions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment