tags:

views:

92

answers:

2
(def throws 10)

(defn r-squared [x y] 
 (+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y))))

(loop [hits 0]
  (let [x (rand)
        y (rand)]
    ; still inside the let
    (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again
        (recur (inc hits)) 
        (* 4 (/ hits throws)))))  

I got that code working and running until the if condition is true. How can I rewrite it so it takes X as parameter and runs X times?

I basically want to call (r-squared 100) and get how many hits I got as return value.

A: 

I think this is what you want, if understend question correctly.

(defn test [n]
  (loop [hits 0 n n]
    (let [x (rand)
          y (rand)]
      (if (< n 0)
          hits ;// you can put (* 4 (/ hits throws)) here
          (if (< (r-squared x y) 0.25)
              (recur (inc hits) (dec n))
              (recur hits (dec n)))))))
jcubic
how do I wrap this in time to get the exeuction time?
peter
Wrap your call to test in time. `(time (test 100))`
Rayne
The code is never changing the value of n. It is equivalent to the poster initial code, for any n bigger than 0.
Nicolas Oury
I put modified version.
jcubic
A: 

Didn't eval it, so parn might be slightly wrong.

(def throws 10)

(defn r-squared [x y] 
 (+ (* (- 0.5 x) (- 0.5 x)) 
    (* (- 0.5 y) (- 0.5 y))))


 (defn test-r-squared [n] 
  (loop [hits (int 0) n (int n)]
   (let [x (rand)
         y (rand)]
    ; still inside the let
    (if (< n 0)
       (* 4 (/ hits throws))
       (if (< (r-squared x y) 0.25) ;is it a hit or not? if not, try again
         (recur (inc hits) (dec n)) 
         (recur hits (dec n)))))))  
Nicolas Oury