Advertisement
Guest User

Untitled

a guest
Aug 24th, 2015
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  (ns Problem1)
  2. (require '[clojure.set :as cs])
  3. ;multiples of 3 and 5
  4.  
  5. (defn answer [maxrange]
  6.   (apply + (filter (fn [x]
  7.                      (or (zero? (mod x 3))
  8.                          (zero? (mod x 5))))
  9.                    (range maxrange))))
  10. (defn answer2 [maxrange]
  11.   (reduce + (filter #(or (zero? (mod % 3))
  12.                          (zero? (mod % 5)))
  13.                     (range maxrange))))
  14.  ; -> 233168
  15.  ; Answer is correct... but can we do better?
  16.  ; Let's try a different approach and time them side by side.
  17.  ; (I suspect set intersection will be more efficient)
  18.  
  19.  
  20. (defn answer3 [maxrange]
  21.   (reduce + (cs/union (set (range 3 maxrange 3))
  22.                      (set (range 5 maxrange 5)))))
  23.  
  24. (println "================ Strategy 1 ================")
  25. (println "Logic: Apply the addition operator to a filtered subset of range(0 1000)")
  26. (println " (answer 1000):" (answer 1000))
  27. (println "       Correct?" (= (answer 1000) 233168))
  28. (println (time (answer 1000)))
  29. (println "Comments: Logic identical to Strategy 2, except uses '(apply [f coll])' instead of '(reduce [f coll])")
  30. (println "")
  31. (println "================= Strategy 2 ===============")
  32. (println "Logic: Reduce a filtered subset of range(0 1000) using the addition operator")
  33. (println "(answer2 1000):" (answer2 1000))
  34. (println "       Correct?" (= (answer2 1000) 233168))
  35. (println (time (answer2 1000)))
  36. (println "Comments: Faster than Strategy 1 by a small constant factor. Cool!")
  37. (println "")
  38. (println "================= Strategy 3 ===============")
  39. (println "Logic: Set union! Reduce the union of two sets (multiples of 3, multiples of 5) using the addition operator")
  40. (println "(answer3 1000):" (answer3 1000))
  41. (println (time (answer3 1000)))
  42. (println "Comments: I suspect this will be among the fastest solutions to this problem.")
  43. (println "          ***EDIT***: I eat my hat. This is way slower than filtering the entire range! I wonder why??")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement