Created
August 4, 2025 14:09
-
-
Save jamtur01/b8fa549e2108864e30bf42acf88479eb to your computer and use it in GitHub Desktop.
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 monster.distance) | |
(defn min-monster-distance | |
"Given a collection of monster positions `positions` (numbers) and a minimum | |
safe separation `d`, return | |
* the smallest distance between any two monsters **if** that distance | |
is less than `d` | |
* -1 if every pair of monsters is at least `d` units apart. | |
Runs in O(n log n) time (due to sorting) and O(n) space." | |
[positions d] | |
(let [sorted (sort positions) | |
;; pair-wise distances between consecutive sorted positions | |
distances (map - (rest sorted) sorted) | |
;; handle zero- or one-monster edge cases | |
min-dist (when (seq distances) (apply min distances))] | |
(if (or (nil? min-dist) ; 0 or 1 monster | |
(>= min-dist d)) ; all distances safe | |
-1 | |
min-dist))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment