Skip to content

Instantly share code, notes, and snippets.

@rlb3
Created November 3, 2012 16:29
Show Gist options
  • Select an option

  • Save rlb3/4007838 to your computer and use it in GitHub Desktop.

Select an option

Save rlb3/4007838 to your computer and use it in GitHub Desktop.
vote count ideas
a = {candidate: "candidate1", weight: 1}
b = {candidate: "candidate1", weight: 1}
c = {candidate: "candidate2", weight: 1}
v = [a, b, c].group_by { |x| x[:candidate] }.map { |k,v| { k => v.inject(0) {|a, h| a + h[:weight]}}}
# => [{"candidate1"=>2}, {"candidate2"=>1}]
h = v.each_with_object({}) { |c,hash|
c.each_pair {|k,v|
hash[k] = v
}
}
# {
# "candidate1" => 2,
# "candidate2" => 1
#}
winner = h.max_by {|k,v| v}
#[
# [0] "candidate1",
# [1] 2
#]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment