Skip to content

Instantly share code, notes, and snippets.

@rsim
Forked from mattetti/ranking.rb
Created March 14, 2010 13:36
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 rsim/331972 to your computer and use it in GitHub Desktop.
Save rsim/331972 to your computer and use it in GitHub Desktop.
def rank(arr)
count = {}
arr.each{|item| count[item] = (count[item]||0) + 1}
rank = 1 # initial ranking
ranking = {}
count.keys.sort.reverse.each{|item| ranking[item] = rank; rank += count[item]}
arr.map{|item| ranking[item]}
end
raise 'code fail!' unless rank([5, 5, 5, 5, 5, 1, 1, 1, 1, 1]) == [1, 1, 1, 1, 1, 6, 6, 6, 6, 6]
ds = []
array_size = 100_000
array_size.times do |n|
ds << rand(n)
end
now = Time.now
rank(ds)
puts "time elapsed: #{Time.now - now}"
# ruby 1.9.1 on my machine: 0.112s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment