Last active
August 29, 2015 14:04
-
-
Save jrunning/8549666d32a6bfa88e41 to your computer and use it in GitHub Desktop.
Ranking an array of integers in Ruby - http://stackoverflow.com/q/25042260/179125
This file contains 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
require "benchmark/ips" | |
def falsetru(a) | |
rank = 1 | |
a.group_by {|x| x } | |
.map { |k,v| | |
ret = [rank] * v.size | |
rank += v.size | |
ret | |
}.flatten | |
end | |
def falsetru_2(a) | |
rank, i = 1, 0 | |
a.map { |x| | |
i += 1 | |
x != a[i-2] ? rank = i : rank | |
} | |
end | |
def sawa(a) | |
a.group_by {|e| e} | |
.each_with_object([]) {|(_, v), arr| arr.concat( [arr.length + 1] * v.length ) } | |
end | |
def jordan(a) | |
run = rank = 0 | |
last_n = nil | |
a.map do |n| | |
run += 1 | |
next rank if n == last_n | |
last_n = n | |
rank += run | |
run = 0 | |
rank | |
end | |
end | |
def iceman(a) | |
a.map {|e| a.index(e) + 1 } | |
end | |
def simong(a) | |
rank = 1 | |
a.each_with_index.map {|value, i| a[i-1] == value ? rank : rank = i + 1 } | |
end | |
def cary_s(a) | |
a.each_with_index | |
.chunk { |e,_| e } | |
.flat_map { |_,arr| [arr.first.last + 1] * arr.size } | |
end | |
test_arr = Array.new(10_000) { rand 100 }.sort.reverse | |
Benchmark.ips do |b| | |
b.report("falsetru") { falsetru test_arr } | |
b.report("falsetru (2)") { falsetru_2 test_arr } | |
b.report("sawa") { sawa test_arr } | |
b.report("Jordan") { jordan test_arr } | |
b.report("Iceman") { iceman test_arr } | |
b.report("simongarnier") { simong test_arr } | |
b.report("Cary Swoveland") { cary_s test_arr } | |
end |
This file contains 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
Calculating ------------------------------------- | |
falsetru 72 i/100ms | |
falsetru (2) 130 i/100ms | |
sawa 100 i/100ms | |
Jordan 165 i/100ms | |
Iceman 1 i/100ms | |
simongarnier 104 i/100ms | |
Cary Swoveland 52 i/100ms | |
------------------------------------------------- | |
falsetru 730.9 (±2.1%) i/s - 3672 in 5.025755s | |
falsetru (2) 1289.9 (±2.7%) i/s - 6500 in 5.042749s | |
sawa 986.9 (±2.1%) i/s - 5000 in 5.068450s | |
Jordan 1644.9 (±1.9%) i/s - 8250 in 5.017334s | |
Iceman 6.4 (±0.0%) i/s - 32 in 5.035015s | |
simongarnier 1053.9 (±1.9%) i/s - 5304 in 5.034452s | |
Cary Swoveland 511.4 (±3.5%) i/s - 2600 in 5.090605s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment