Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns Problem1)
- (require '[clojure.set :as cs])
- ;multiples of 3 and 5
- (defn answer [maxrange]
- (apply + (filter (fn [x]
- (or (zero? (mod x 3))
- (zero? (mod x 5))))
- (range maxrange))))
- (defn answer2 [maxrange]
- (reduce + (filter #(or (zero? (mod % 3))
- (zero? (mod % 5)))
- (range maxrange))))
- ; -> 233168
- ; Answer is correct... but can we do better?
- ; Let's try a different approach and time them side by side.
- ; (I suspect set intersection will be more efficient)
- (defn answer3 [maxrange]
- (reduce + (cs/union (set (range 3 maxrange 3))
- (set (range 5 maxrange 5)))))
- (println "================ Strategy 1 ================")
- (println "Logic: Apply the addition operator to a filtered subset of range(0 1000)")
- (println " (answer 1000):" (answer 1000))
- (println " Correct?" (= (answer 1000) 233168))
- (println (time (answer 1000)))
- (println "Comments: Logic identical to Strategy 2, except uses '(apply [f coll])' instead of '(reduce [f coll])")
- (println "")
- (println "================= Strategy 2 ===============")
- (println "Logic: Reduce a filtered subset of range(0 1000) using the addition operator")
- (println "(answer2 1000):" (answer2 1000))
- (println " Correct?" (= (answer2 1000) 233168))
- (println (time (answer2 1000)))
- (println "Comments: Faster than Strategy 1 by a small constant factor. Cool!")
- (println "")
- (println "================= Strategy 3 ===============")
- (println "Logic: Set union! Reduce the union of two sets (multiples of 3, multiples of 5) using the addition operator")
- (println "(answer3 1000):" (answer3 1000))
- (println (time (answer3 1000)))
- (println "Comments: I suspect this will be among the fastest solutions to this problem.")
- (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