Skip to content

Instantly share code, notes, and snippets.

@skydevht
Last active September 24, 2022 01:59
Show Gist options
  • Save skydevht/0c01f48fbf91b065c9c5e31f5b61b3df to your computer and use it in GitHub Desktop.
Save skydevht/0c01f48fbf91b065c9c5e31f5b61b3df to your computer and use it in GitHub Desktop.
(defn fill-rank [cnt score ranks]
(concat (repeat cnt score ranks)))
(defn climbingLeaderboard [ranked player]
(vec (loop
;; the following define our state for the iteration
[rem-rkd ranked ; remaining ranked scores to go through
lts-rkd (first ranked); previous ranked score
rem-pl player ; remaining player to go through
lst-rnk 1 ; latest rank
ranks '()] ; holding the ranks of the player
(let [pl-sc (peek rem-pl)
rk-sc (first rem-rkd)]
(cond
;; base cases
;; no player score, we return the ranks
(nil? pl-sc) ranks
;; no rank scoes, every remaining player
;; score is outside of the ranks
;; remaining player get all the same score
(nil? rk-sc) (fill-rank (count rem-pl)
(+ 1 lst-rnk)
ranks)
;; calculating the next state for the iteration; We used a double
;; cursor. Either we are scrolling down the list of ranked scores, (1 to m)
;; to see if a player score can fit between two. Or we are scrolling
;; down the list of players (n to 1) to see if we can fit more players where
;; we paused on the list of ranked scores
;; The number of iteration will be n + m
:else (let
;; Can the player score be placed before all the
;; remaining ranked scores?
[rf? (>= pl-sc rk-sc)
;; Making sure the current rank is computed
;; We know they are in descending order
rank (if (> lts-rkd rk-sc)
(+ 1 lst-rnk)
lst-rnk)
;; By placing the player score in front of the others,
;; we are always sure its rank is the rank above
nxt-ranks (if rf?
(conj ranks rank) ; adding it in front
ranks)
;; We temporarely moved our player score to the front
;; pausing the processing of the rank, to see if
;; there are not other scores that can fit the bill
nxt-rem-rkd (if rf?
rem-rkd
(subvec rem-rkd 1))
;; If we paused the processing of the ranks, we need
;; to process the player's score, to see if we can fit
;; another one before the list.
nxt-rem-pl (if rf? (pop rem-pl) rem-pl)]
;; starting a new iteration with our computed state
(recur nxt-rem-rkd
rk-sc
nxt-rem-pl
rank
nxt-ranks)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment