Created
March 14, 2010 07:40
-
-
Save mattetti/331824 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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