Last active
March 3, 2023 03:26
-
-
Save chase-lambert/cb64e8a0d415c6f04b63aca3f5d02a4d to your computer and use it in GitHub Desktop.
random nerd snipe messing around
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns area | |
(:require | |
[clojure.math :as math] | |
[criterium.core :as crit])) | |
(defmulti area :shape) | |
(defmethod area :square [{:keys [side]}] | |
(* side side)) | |
(defmethod area :rectangle [{:keys [width height]}] | |
(* width height)) | |
(defmethod area :triangle [{:keys [base height]}] | |
(* 0.5 base height)) | |
(defmethod area :circle [{:keys [radius]}] | |
(* math/PI radius radius)) | |
(defn make-random-shape [] | |
(let [shapes [:square :rectangle :circle :triangle] | |
shape (rand-nth shapes) | |
lengths (case shape | |
:square {:side (rand-int 10)} | |
:rectangle {:width (rand-int 10) | |
:height (rand-int 10)} | |
:triangle {:base (rand-int 10) | |
:height (rand-int 10)} | |
:circle {:radius (rand-int 10)})] | |
(merge {:shape shape} lengths))) | |
(defn total-area [shapes] | |
(transduce (map area) + shapes)) | |
(def lots-of-shapes (doall (repeatedly 400000 #(make-random-shape)))) | |
(crit/bench (total-area lots-of-shapes)) ;; 56 ms which is 56,000 microseconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment