Advertisement
Guest User

Enumeration of integer expressions which only contains 8s

a guest
Sep 28th, 2013
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. open Printf
  2.  
  3. type exp =
  4. | Impossible
  5. | Eight
  6. | Add of exp * exp
  7. | Sub of exp * exp
  8. | Div of exp * exp
  9. | Mul of exp * exp
  10. | Sqrt of exp
  11.  
  12. let rec print out = function
  13. | Impossible -> ()
  14. | Eight -> fprintf out "8"
  15. | Add (a,b) -> fprintf out "(%a + %a)" print a print b
  16. | Sub (a,b) -> fprintf out "(%a - %a)" print a print b
  17. | Div (a,b) -> fprintf out "(%a / %a)" print a print b
  18. | Mul (a,b) -> fprintf out "(%a * %a)" print a print b
  19. | Sqrt (a) -> fprintf out "sqrt(%a)" print a
  20.  
  21. let n = 256
  22. let c = 4
  23.  
  24. let mem = Array.init c (fun _ -> Array.make n Impossible)
  25.  
  26. let rec enum exp count value =
  27.   if value > 0 && value <= n &&
  28.      count > 0 && count <= c &&
  29.      mem.(count-1).(value-1) = Impossible then
  30.   begin
  31.     mem.(count-1).(value-1) <- exp ;
  32.  
  33.     if count < c then
  34.     begin
  35.       for i = 0 to c-1 do
  36.         for j = 0 to n-1 do
  37.           let exp' = mem.(i).(j)
  38.           and count' = i+1
  39.           and value' = j+1 in
  40.           if exp' <> Impossible then
  41.           begin
  42.             enum (Add (exp, exp')) (count + count') (value + value') ;
  43.             enum (Sub (exp, exp')) (count + count') (value - value') ;
  44.             enum (Sub (exp', exp)) (count + count') (value' - value) ;
  45.             enum (Mul (exp, exp')) (count + count') (value * value') ;
  46.             if value mod value' = 0 then
  47.               enum (Div (exp, exp')) (count + count') (value / value') ;
  48.             if value' mod value = 0 then
  49.               enum (Div (exp', exp)) (count + count') (value' / value) ;            
  50.           end
  51.         done
  52.       done
  53.     end ;
  54.  
  55.     let froot = sqrt (float_of_int value) in
  56.     let iroot = int_of_float froot in
  57.     if float_of_int iroot = froot then
  58.       enum (Sqrt exp) count iroot ;
  59.   end
  60.  
  61. let _ =
  62.   enum Eight 1 8 ;
  63.   for j = 0 to 29 do
  64.     printf "%d: %a\n" (j+1) print mem.(c-1).(j) ;
  65.   done
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement