Skip to content

Instantly share code, notes, and snippets.

@mhelfer
Created November 27, 2013 05:14
Show Gist options
  • Save mhelfer/7670955 to your computer and use it in GitHub Desktop.
Save mhelfer/7670955 to your computer and use it in GitHub Desktop.
beginning = Time.now
def doRound (votePools, votes, round)
votes.each do |voter|
#check to see if the votepool contains the candidate
voter.each do |vote|
if votePools.has_key?(vote)
votePools[vote].push(voter)
break
end
end
end
end
candidates = [:mark, :merrill, :neal, :troy, :alicia, :edmund, :bob, :jackie, :christopher, :dan, :james, :cyd]
#Generate some votes
perms = candidates.permutation(3).to_a
votes = 1000000.times.collect{ perms[ rand(perms.length) ] }
totalVotes = votes.length
#Store votes for each candidate in a hash of arrays
votePools = {}
candidates.each do |candidate|
votePools[candidate] = []
end
winner = false
round = 0
while winner != true do
doRound votePools, votes, round
sorted = votePools.sort_by{|k,v| -v.length};
sorted.each do |x|
print "#{x[0]}=#{x[1].length} "
end
print "\n"
if(sorted.first[1].length.to_f / totalVotes.to_f > 0.5)
puts "winner = candiate #{sorted.first[0]}"
winner = true
elsif (sorted.length == 1)
puts "winner = candiate #{sorted.first[0]}"
winner = true
else
votes = sorted.last[1]
votePools.delete(sorted.last[0])
end
end
puts "Time elapsed #{Time.now - beginning} seconds"
beginning = Time.now
#make one ballot
names = [:mark, :merrill, :neal, :troy, :alicia, :edmund, :bob, :jackie, :christopher, :dan, :james, :cyd]
# find all permutations of the ballot
perms = names.permutation(3).to_a
pc = perms.length
puts "#{pc} possible ballot permutations"
# get a bunch of random ballots
votes = 1000000.times.collect{ perms[ rand(pc) ] }
def is_anyone_majority(ballots)
majority = ballots.count / 2
counts = Hash.new(0)
ballots.each{|x| counts[x[0]] += 1 }
biggest = counts.max_by{|x| x[1] }
if biggest[1] > majority
puts counts.inspect
puts biggest[0]
else
smallest = counts.min_by{|x| x[1] }
puts counts.inspect
eliminate_last_place(ballots,smallest[0])
end
end
def eliminate_last_place(all_ballots, last_place)
is_anyone_majority( all_ballots.collect{|ranked_ballot| (ranked_ballot - [last_place]).delete_if{|x| x == [] } }.delete_if{|x| x == []} )
end
is_anyone_majority(votes)
puts "Time elapsed #{Time.now - beginning} seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment