summaryrefslogtreecommitdiff
path: root/90-94/93.hs
blob: c031e7b071c31118102e27d01a19816a9ef65c61 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
puzzle :: [Integer] -> [String]

puzzle l = do i <- [1..length l-1]
              let (subl, subr) = splitAt i l
              (sl, vl, _) <- gen subl
              (sr, vr, _) <- gen subr
              if vl == vr then
                  return (sl ++ " = " ++ sr)
              else []

gen :: [Integer] -> [(String, Rational, String)]
gen (x:[]) = return (show x, fromInteger x, "_")

gen l = do i <- [1..length l-1]
           let (subl, subr) = splitAt i l
           (sl, vl, opsl) <- gen subl
           (sr, vr, opsr) <- gen subr
           (ops, op) <- [("+", (+)), ("-", (-)), ("*", (*)), ("/", (/))]
           if (ops == "/" && vr == 0) ||
               (ops == "+" && (opsr == "+" || opsr == "-")) ||
               (ops == "*" && (opsr == "*" || opsr == "/")) then []
           else
              return ((if opsl /= "_" &&
                          (ops == "*" || ops == "/") &&
                          (opsl == "+" || opsl == "-") then
                           "(" ++ sl ++ ")"
                      else sl)
                      ++ " " ++ ops ++ " " ++
                      (if opsr /= "_" &&
                           ((ops == "-" && opsr /= "*" && opsr /= "/") ||
                           (ops == "*" && (opsr == "+" || opsr == "-")) ||
                           ops == "/") then
                           "(" ++ sr ++ ")"
                      else sr), op vl vr, ops)