Advertisement
Guest User

Untitled

a guest
Feb 14th, 2012
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.99 KB | None | 0 0
  1. let getSubsets list =
  2.     let rec generateSubsets list acc compacc =
  3.         seq {
  4.             match list with
  5.             | [] -> yield acc
  6.             | head::tail ->
  7.                 yield! generateSubsets tail (head::acc) compacc
  8.                 yield! generateSubsets tail acc (head::compacc)
  9.         }
  10.    
  11.     (generateSubsets list [] []) |> Seq.toArray
  12.  
  13. let getResults list =
  14.     let getCalcString calcstr op head =
  15.         if calcstr = "" then
  16.             head
  17.         else
  18.             calcstr + " " + op + " " + head
  19.  
  20.     let rec loop list result calcstr =
  21.         seq {
  22.             match list with
  23.             | [] -> yield (result, calcstr)
  24.             | head::tail ->
  25.                 let headstr = head.ToString()
  26.                 yield! loop tail (result + head) (getCalcString calcstr "+" headstr)
  27.                 yield! loop tail (result - head) (getCalcString calcstr "-" headstr)
  28.                 yield! loop tail (head - result) (getCalcString headstr "-" calcstr)
  29.                 yield! loop tail (result * head) (getCalcString calcstr "*" headstr)
  30.                 if head <> 0 then
  31.                     yield! loop tail (result / head) (getCalcString calcstr "/" headstr)
  32.                 if result <> 0 then
  33.                     yield! loop tail (head / result) (getCalcString headstr "/" calcstr)
  34.         }
  35.  
  36.     let run list =
  37.         match list with
  38.         | [] -> Seq.empty
  39.         | head::tail -> loop tail head (head.ToString())
  40.  
  41.     run list
  42.  
  43. // only works for sets with 3 numbers or larger
  44. let calculate subsets =
  45.     if subsets |> Array.length < 8 then
  46.         ()
  47.     else
  48.         for i in 1..subsets.Length/2 do
  49.             (getResults subsets.[i])
  50.             |> Seq.iter(fun (result, calcstr) ->
  51.                 (getResults subsets.[subsets.Length-1-i])
  52.                 |> Seq.iter(fun (result2, calcstr2) ->
  53.                     if result = result2 then
  54.                         printfn "%s = %s "calcstr calcstr2))
  55.    
  56.  
  57. calculate (getSubsets [1;2;3;6])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement