fork download
  1. import Data.List
  2.  
  3. main :: IO ()
  4. main =
  5. mapM_ (print . find4A)
  6. [
  7. "1 5 3 6 : 10"
  8. , "1 5 3 6 7 : 10"
  9. , "1 2 3 4 5 : 10"
  10. , "1 2 3 4 5 6 7 8 : 10"
  11. ]
  12.  
  13. find4A :: String -> [String]
  14. find4A s = filter ((== y) . eval4A) exprs
  15. where
  16. exprs = combo $ [x1] : map addOperators xs
  17. x1:xs = words xs0
  18. y = read $ tail y0
  19. (xs0, y0) = break (==':') s
  20. addOperators :: String -> [String]
  21. addOperators x = map (++ x) [" + ", " - ", " * ", " / "]
  22.  
  23. combo :: [[[a]]] -> [[a]]
  24. combo (x:xs) = combo' x xs
  25. where
  26. combo' ys [] = ys
  27. combo' ys (h:t) = combo' [y ++ z | y <- ys, z <- h] t
  28. combo _ = []
  29.  
  30. eval4A :: String -> Double
  31. eval4A s = go (map read xxs) yys
  32. where
  33. (xxs, yys) = partition (`notElem` ["+", "-", "*", "/"]) $ words s
  34. go [x1] _ = x1
  35. go (x1:x2:xs) ("*":ys) = go ((x1 * x2) : xs) ys
  36. go (x1:x2:xs) ("/":ys) = go ((x1 / x2) : xs) ys
  37. go (x1:xs) ("+":ys) = x1 + go xs ys
  38. go (x1:x2:xs) ("-":ys) = x1 + go ((-x2) : xs) ys
  39. go _ _ = -1
  40.  
Success #stdin #stdout 0.95s 6304KB
stdin
Standard input is empty
stdout
["1 + 5 * 3 - 6","1 * 5 / 3 * 6"]
["1 + 5 + 3 - 6 + 7"]
["1 + 2 + 3 * 4 - 5"]
["1 + 2 + 3 + 4 + 5 - 6 - 7 + 8","1 + 2 + 3 + 4 - 5 + 6 + 7 - 8","1 + 2 - 3 - 4 + 5 - 6 + 7 + 8","1 + 2 * 3 * 4 - 5 * 6 + 7 + 8","1 - 2 + 3 + 4 - 5 - 6 + 7 + 8","1 - 2 + 3 - 4 + 5 + 6 - 7 + 8","1 - 2 + 3 * 4 * 5 / 6 - 7 + 8","1 - 2 + 3 / 4 + 5 + 6 * 7 / 8","1 - 2 - 3 + 4 + 5 + 6 + 7 - 8","1 - 2 - 3 - 4 * 5 + 6 * 7 - 8","1 - 2 * 3 + 4 * 5 - 6 - 7 + 8","1 * 2 + 3 * 4 + 5 + 6 - 7 - 8","1 * 2 - 3 + 4 * 5 + 6 - 7 - 8","1 * 2 - 3 - 4 + 5 * 6 - 7 - 8","1 * 2 * 3 + 4 + 5 - 6 - 7 + 8","1 * 2 * 3 + 4 - 5 + 6 + 7 - 8","1 * 2 * 3 * 4 - 5 + 6 - 7 - 8","1 / 2 - 3 / 4 + 5 + 6 * 7 / 8","1 / 2 * 3 * 4 - 5 - 6 + 7 + 8","1 / 2 / 3 - 4 + 5 / 6 * 7 + 8"]