|
| 1 | +(ns advent-of-code-clj.utils-test |
| 2 | + (:require |
| 3 | + [advent-of-code-clj.utils :as utils] |
| 4 | + [clojure.test :refer [deftest is testing]])) |
| 5 | + |
| 6 | +(deftest binary-search-test |
| 7 | + (testing "Finds last valid value" |
| 8 | + (let [numbers (vec (range 0 1000000 19)) |
| 9 | + found-index (utils/binary-search #(> 100006 (numbers %)) 0 (dec (count numbers)))] |
| 10 | + (is (> (numbers (inc found-index)) 100006 (numbers found-index))))) |
| 11 | + (testing "Finds first valid value" |
| 12 | + (let [numbers (vec (range 0 1000000 19)) |
| 13 | + found-index (utils/binary-search #(< 100006 (numbers %)) 0 (dec (count numbers)))] |
| 14 | + (is (< (numbers (dec found-index)) 100006 (numbers found-index))))) |
| 15 | + (testing "Inverted greater-than/less-than does not find same value" |
| 16 | + (let [numbers (vec (range 0 1000000 19)) |
| 17 | + found-index (utils/binary-search #(< 100006 (numbers %)) 0 (dec (count numbers))) |
| 18 | + found-index-2 (utils/binary-search #(> 100006 (numbers %)) 0 (dec (count numbers)))] |
| 19 | + (is (not= found-index found-index-2))) |
| 20 | + (let [numbers (vec (range 0 1000000)) |
| 21 | + middle-value (/ 1000000 2) |
| 22 | + found-index (utils/binary-search #(<= middle-value (numbers %)) 0 (dec (count numbers))) |
| 23 | + found-index-2 (utils/binary-search #(> middle-value (numbers %)) 0 (dec (count numbers)))] |
| 24 | + (is (= 500000 found-index)) |
| 25 | + (is (= 499999 found-index-2)) |
| 26 | + (is (not= found-index found-index-2)))) |
| 27 | + (testing "Throws when no value can be found" |
| 28 | + (let [numbers (vec (range 0 1000000 19))] |
| 29 | + (is (thrown? Exception (utils/binary-search #(= 199 (numbers %)) 0 (dec (count numbers)))))) |
| 30 | + (let [numbers (vec (repeat 1000 0))] |
| 31 | + (is (thrown? Exception (utils/binary-search #(= 0 (numbers %)) 0 (dec (count numbers)))))) |
| 32 | + (let [numbers (vec (concat (range 0 400) (range 1000 0) (range 0 400)))] |
| 33 | + (is (thrown? Exception (utils/binary-search #(> (numbers %) 500) 0 (dec (count numbers)))))))) |
0 commit comments