Skip to content

Instantly share code, notes, and snippets.

@stuarthalloway
Created May 20, 2018 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuarthalloway/6fb3c4f155242e2eb94f4a3060528bab to your computer and use it in GitHub Desktop.
Save stuarthalloway/6fb3c4f155242e2eb94f4a3060528bab to your computer and use it in GitHub Desktop.
(defn round5
"Round to the closest positive multiple of 5.
Negative numbers round to 0, which is not
considered a multiple of 5."
{:test (fn [] (let [roundsto (fn [e] #(= e (round5 %)))]
(testing "Negative numbers"
(is (every? (roundsto 0) (range -20 0))))
(testing "Positive numbers rounding to 5"
(is (every? (roundsto 5) (range 0 8))))
(testing "Positive numbers rounding not to 5"
(is (every? (roundsto 10) (range 8 13)))
(is (every? (roundsto 20) (range 18 23)))
(is (= 1020 (round5 1022))))))}
[n]
(cond (< n 0)
0
(< n 8)
5
:else
(let [remainder (rem n 5)
quotient (quot n 5)]
(* 5 (+ quotient
(if (<= remainder 2)
0
1))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment