Rosetta Code
Top rank per group
Pick the highest-scoring row from each group with a stable tie-break on name.
Source
rosettacode/popular/top_rank_per_group.vibe
# title: Top rank per group
# source: https://rosettacode.org/wiki/Top_rank_per_group
# category: Rosetta Code
# difficulty: Intro
# summary: Pick the highest-scoring row from each group with a stable tie-break on name.
# tags: popular, arrays, ranking, hashes
# vibe: 0.2
def rows
[
{ group: "blue", name: "Ava", score: 92 },
{ group: "blue", name: "Ben", score: 88 },
{ group: "green", name: "Noah", score: 77 },
{ group: "green", name: "Mia", score: 91 },
{ group: "red", name: "Zoe", score: 84 },
{ group: "red", name: "Eli", score: 84 }
]
end
def better_rank?(candidate, current)
if current == nil
true
elsif candidate[:score] > current[:score]
true
elsif candidate[:score] < current[:score]
false
else
candidate[:name] < current[:name]
end
end
def top_rank_per_group(rows)
best = {}
index = 0
while index < rows.length
row = rows[index]
key = row[:group]
if better_rank?(row, best[key])
best[key] = row
end
index = index + 1
end
groups = ["blue", "green", "red"]
output = []
index = 0
while index < groups.length
output = output.push(best[groups[index]])
index = index + 1
end
output
end
def run
top_rank_per_group(rows)
end
Output
Press run to execute run from this example.