fork download
  1. import Data.List
  2. main :: IO ()
  3. main = mapM_ (print . find4A) ["1 5 3 6 : 10", "1 5 3 6 7 : 10"]
  4. find4A :: String -> [String]
  5. find4A s = (flip (map . (!!)) =<< elemIndices y . map expr) $ combo [x1] opPlusDigitList
  6. where
  7. combo as [] = as
  8. combo as (h:t) = combo [a ++ b | a <- as, b <- h] t
  9. opPlusDigitList = map (\x -> [op ++ x | op <- ops]) $ xs
  10. (xs0, y0) = break (==':') s
  11. x1:xs = words xs0
  12. y = read $ tail y0 :: Double
  13. ops = [" + ", " - ", " * ", " / "]
  14. expr :: String -> Double
  15. expr s = go (map read xxs) yys
  16. where
  17. (xxs, yys) = partition (`notElem` ["+", "-", "*", "/"]) $ words s
  18. go [x1] _ = x1
  19. go (x1:x2:xs) ("*":ys) = go ((x1 * x2) : xs) ys
  20. go (x1:x2:xs) ("/":ys) = go ((x1 / x2) : xs) ys
  21. go (x1:xs) ("+":ys) = x1 + go xs ys
  22. go (x1:x2:xs) ("-":ys) = x1 + go ((-x2) : xs) ys
  23. go _ _ = -1
  24.  
Success #stdin #stdout 0.01s 6352KB
stdin
Standard input is empty
stdout
["1 + 5 * 3 - 6","1 * 5 / 3 * 6"]
["1 + 5 + 3 - 6 + 7"]