Created
April 1, 2018 19:28
-
-
Save gamesbook/fd92833d054fbfac5d23912828f83b2d to your computer and use it in GitHub Desktop.
Histogram for two dice of any size
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
""" | |
https://stackoverflow.com/questions/33454739/distribution-of-dice-rolls | |
& | |
https://stackoverflow.com/questions/20335617/unlimited-sides-to-dice-in-simulator/ | |
""" | |
from collections import Counter | |
import sys | |
from random import randint | |
# Python 2/3 compatibility | |
if sys.hexversion >= 0x3000000: | |
inp = input | |
rng = range | |
else: | |
inp = raw_input | |
rng = xrange | |
def get_int(prompt, default=6): | |
"""Convert string to an int.""" | |
while True: | |
try: | |
return int(inp(prompt)) | |
except ValueError: | |
return default | |
def single_bar(val, value, scale): | |
"""Print a single bar for the histogram.""" | |
print('{:>2} {} {}'.format(val, '#'*int(value*scale + 0.5), value)) | |
def histogram(results, maxbar=76): | |
"""Create and then print the histogram.""" | |
# find the histogram domain | |
values = list(results.keys()) | |
_lo, _hi = min(values), max(values) | |
# find the data range | |
scale = maxbar / float(max(results.values())) | |
# output the results | |
for val in rng(_lo, _hi + 1): | |
single_bar(val, results[val], scale) | |
def main(): | |
"""Main""" | |
side1 = get_int("How many sides does your first die have? ") | |
side2 = get_int("How many sides does your second die have? ") | |
times = get_int("How many times do you want to roll? ", default=100000) | |
maxbar = get_int("How long is your max bar? ", default=76) | |
results = Counter( | |
(randint(1, side1) + randint(1, side2)) for roll in rng(times)) | |
print("\nProcessed %s rolls for a d%s and a d%s...\n" % | |
(times, side1, side2)) | |
histogram(results, maxbar=maxbar) | |
print("\n") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment