Skip to content

Commit 8302c1f

Browse files
committed
Create improved alternatives for countdown problem
1 parent 5d2df78 commit 8302c1f

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

09-the-countdown-problem/09.11-exercises.hs

+27-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,6 @@ exprs ns = [e | (ls, rs) <- split ns,
108108
r <- exprs rs,
109109
e <- combine l r]
110110

111-
-- | Combines each pair of expressions using the four numeric operators.
112111
combine :: Expr -> Expr -> [Expr]
113112
combine l r = [App o l r | o <- ops]
114113

@@ -125,3 +124,30 @@ solutions ns n =
125124

126125
main :: IO ()
127126
main = print (solutions [1,3,7,10,25,50] 765)
127+
128+
type Result = (Expr, Int)
129+
130+
-- | Returns all possible results comprising expressions whose list of values
131+
-- is precisely a given list.
132+
--
133+
-- For the empty list there are no possible results.
134+
-- For a single number there is a single result formed from that number.
135+
-- Otherwise, for two or more numbers we first produce all splittings of the
136+
-- list, then recursively calculate all possible results for each of these
137+
-- lists
138+
-- Finally, combine each of the four numeric operators that are valid.
139+
results :: [Int] -> [Result]
140+
results [] = []
141+
results [n] = [(Val n, n) | n > 0]
142+
results ns = [res | (ls, rs) <- split ns,
143+
lx <- results ls,
144+
ry <- results rs,
145+
res <- combine' lx ry]
146+
147+
combine' :: Result -> Result -> [Result]
148+
combine' (l,x) (r,y) =
149+
[(App o l r, apply o x y) | o <- ops, valid o x y]
150+
151+
solutions' :: [Int] -> Int -> [Expr]
152+
solutions' ns n =
153+
[e | ns' <- choices ns, (e, m) <- results ns', m == n]

0 commit comments

Comments
 (0)