Skip to content

Instantly share code, notes, and snippets.

@mattetti
Created March 14, 2010 07:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mattetti/331824 to your computer and use it in GitHub Desktop.
Save mattetti/331824 to your computer and use it in GitHub Desktop.
def rank(arr)
# creating a dataset hash with each entry looking like that:
# key -> value
# value -> index in array
ds = {}
arr.each_with_index do |item, index|
ds[item] ||= []
ds[item] << index
end
result = []
rank = 1
ds.keys.sort.reverse.each do |value|
ds[value].each do |value_index|
result[value_index] = rank
end
rank += ds[value].length
end
result
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.2 on my machine: 0.156s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment