Skip to content

Instantly share code, notes, and snippets.

@jamtur01
Created August 4, 2025 14:09
Show Gist options
  • Save jamtur01/b8fa549e2108864e30bf42acf88479eb to your computer and use it in GitHub Desktop.
Save jamtur01/b8fa549e2108864e30bf42acf88479eb to your computer and use it in GitHub Desktop.
(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