Commits

Joby Poriyath committed 2f840c4

triple sum and timing function

Comments (0)

Files changed (4)

 #directory "_build";;
-#load "util.cmo";;
+#load "util.cmo";;
+let triple_sum a = 
+  let n = (Array.length a - 1) in
+  let count = ref 0 in
+  for i = 0 to n do
+    for j = (i + 1) to n do
+      for k = (j + 1) to n do
+        if ((a.(i) + a.(j) + a.(k)) = 0) then
+          count := !count + 1
+      done
+    done
+  done;
+  !count
+
+let main n =
+  let n = (if !Sys.interactive then n else int_of_string Sys.argv.(1)) in
+  let a = Array.make (n * 1024) 0 in
+  for i = 0 to Array.length a - 1 do
+    a.(i) <- Util.random_int 1_000_000
+  done;
+  let time_taken, result = Util.time_it triple_sum a in
+  Printf.printf "result = %d time_taken = %f \n" result time_taken
+    
+let _ = main 1
   | [] -> ""
   | (w::ws) -> (w ^ s) ^ join s ws
 
+let time_it action arg = 
+  let t1 = Sys.time () in
+  let result = action arg in
+  let t2 = Sys.time () in
+  (t2 -. t1, result)
+
+let random_int n =
+  match Random.bool () with
+    | true -> Random.int n
+    | false -> -1 * (Random.int n)
+
+let _ = Random.self_init ()
+
 (* end of utility functions *)
 val split_on : (char -> bool) -> string -> string list
 val split : string -> string list
 val join : string -> string list -> string
+val time_it : ('a -> 'b) -> 'a -> float * 'b
+val random_int : int -> int