#!/usr/bin/python
import random
import sys

"""
What is the average of rolling 2d6 and taking the lowest or highest result?

Paul Gorman (http://quicklyquietlycarefully.blogspot.com/)
26 Nov 2012
"""

numberOfRolls = 100000
samples = 25
rollsControl = []
rollsGreater = []
rollsLesser = []

def median(a):
    sortedArray = sorted(a)
    aLength = len(sortedArray)
    return int(0.5 * ( sortedArray[(aLength - 1)//2] + sortedArray[aLength//2]))

def mode(values):
    return max(set(values), key=values.count)

def d6():
    return random.randint(1,6)

def getGreater(roll0, roll1):
    if roll0 > roll1:
        return roll0
    return roll1

def getLesser(roll0, roll1):
    if roll0 < roll1:
        return roll0
    return roll1

for i in range(numberOfRolls):
    rollsControl.append(d6())
    rollsGreater.append(getGreater(d6(), d6()))
    rollsLesser.append(getLesser(d6(), d6()))

sys.stdout.write("\n")
print "--- Results for " + str(numberOfRolls) + " Rolls ---"
print "Mean of 1d6: " + str(float(sum(rollsControl)) / float(len(rollsControl)))
print "Mean of 2d6 take the greater: " + str(float(sum(rollsGreater)) / float(len(rollsGreater)))
print "Mean of 2d6 take the lesser: " + str(float(sum(rollsLesser)) / float(len(rollsLesser)))
print "---"
print "Median of 1d6: " + str(median(rollsControl))
print "Median of 2d6 take the greater: " + str(median(rollsGreater))
print "Median of 2d6 take the lesser: " + str(median(rollsLesser))
print "---"
print "Mode of 1d6: " + str(mode(rollsControl))
print "Mode of 2d6 take the greater: " + str(mode(rollsGreater))
print "Mode of 2d6 take the lesser: " + str(mode(rollsLesser))
sys.stdout.write("\n")
print "--- Sampling of Rolls (Sanity Check) ---"
sys.stdout.write("Control sample numbers: ")
for i in range(samples):
    sys.stdout.write(" " + str(rollsControl[i]) + " ")
sys.stdout.write("\n")
sys.stdout.write("Greater sample numbers: ")
for i in range(samples):
    sys.stdout.write(" " + str(rollsGreater[i]) + " ")
sys.stdout.write("\n")
sys.stdout.write("Lesser sample numbers: ")
for i in range(samples):
    sys.stdout.write(" " + str(rollsLesser[i]) + " ")
sys.stdout.write("\n\n")
