Skip to content

Instantly share code, notes, and snippets.

@dbechrd
Last active January 25, 2019 01:01
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 dbechrd/7ae203f39626fe0a0b0de71a7ef391bd to your computer and use it in GitHub Desktop.
Save dbechrd/7ae203f39626fe0a0b0de71a7ef391bd to your computer and use it in GitHub Desktop.
# Complete the climbingLeaderboard function below.
def climbingLeaderboard(scores, alice)
# Store Alice's position after each game
results = []
# Keep track of Alice's high score so far
alice_max = 0
# For each of Alice's scores
alice.map do |alice_score|
# Update Alice's high score
if alice_score > alice_max
alice_max = alice_score
else
# High score didn't change, Alice is in the same place
results << results.last
next
end
# Flag to track if we found a place for Alice's score in the leaderboard
# If false, she's at the bottom of the leaderboard and we need to add 1
found = false
# Keep track of previous score in leaderboard to de-duplicate the data
last_score = scores[0]
# Keep track of what place the current score is in after de-duplication
place = 1
# For each score in the leaderboard
scores.map do |score|
# If not the same as the previous score, we're at the next place in the
# leaderboard
if score < last_score
place += 1
end
# If Alice's high score is better than or equal to the current score,
# she will take or tie for this place. We found her place, so we can
# stop searching
if alice_max >= score
found = true
break
end
# Update the last_score de-duplication variable in preparation for
# the next iteration of this loop
last_score = score
end
# We didn't find a place for Alice in the leaderboard, so she's at the
# bottom, 1 place past current last place holder.
if !found
place += 1
end
# Record Alice's current place in the leaderboard in the results array
results << place
end
# Return the results
results
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment