Created
November 19, 2015 17:34
-
-
Save wadtech/30c1843e75f1d96d3b0d to your computer and use it in GitHub Desktop.
Dice example with tally for frequency of results
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
puts "How many times do you want to roll?" | |
choice = gets.chomp | |
puts "How many sides should dice have?" | |
sides = gets.chomp | |
c = choice.to_i | |
s = sides.to_i | |
# store our tally of results in a hash with a default value | |
# for uninitialized members of 0 | |
results = Hash.new(0) | |
puts "Rolling" | |
c.times do | |
roll = rand(1...s) # instead of adding one to the roll each time, we can rand from a range | |
results[roll] += 1 # because the default is 0, we can simply increment a missing value | |
end | |
puts "How many times did each roll appear?" | |
# display a heading for our data | |
puts "Result\tTimes Rolled" | |
# sort the hash by 'last', that is the value- the key is the first value in each pair. | |
# reverse it to put the most frequent to the front of the list | |
# convert into a hash again because sort_by leaves us with a nested array structure. | |
results.sort_by(&:last).reverse.to_h.each do |k, v| | |
# print the results under our heading | |
puts "#{k}\t#{v}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment