# -*- coding: utf-8 -*-
import random
import time

class Bag:
	def __init__(self, contents):
		self.stones = []
		self.contents = contents
		for color in contents.keys():
			count = contents[color]
			for i in range(0,count):
				self.stones.append(color)
	
	def __str__(self):
		line = ""
		colors = self.contents.keys()
		colors.sort()
		for color in colors:
			line += "%s=%d " % (color,self.contents[color])
		return line.strip()
	
	def draw(self, count):
		random.shuffle(self.stones)
		return self.stones[:count]

class Simulation:
	def __init__(self,description,bag,drawCount=5,success=("B")):
		self.description = description
		self.bag = bag
		self.repetitions = 0
		self.results = []
		self.drawCount = drawCount
		self.success = success
		for i in range(0,drawCount + 1):
			self.results.append({'count': 0})

	
	def run(self,repetitions):
		start = time.clock();
		for i in range(0,repetitions):
			result = self.oneDraw()
			(successes,remainder) = self.countSuccess(result)
			tier = self.results[successes]
			tier['count'] += 1;
			if remainder:
				try:
					tier[remainder] += 1;
				except:
					tier[remainder] = 1;
		self.repetitions += repetitions
		end = time.clock()
		self.duration = end - start
	
	def countSuccess(self,result):
		successes = 0
		remainder = result
		for color in self.bag.contents.keys():
			if color in self.success:
				successes += result.count(color)
				remainder = remainder.replace(color,'')
		return (successes,remainder)
	
	def oneDraw(self):
		result = self.bag.draw(self.drawCount)
		result.sort()
		resultStr = ''.join(result)
		return resultStr
	
	def report(self):
		print "%s (%s) [%.2f seconds @ %.2f tests/sec]" % (self.description, self.bag, self.duration, self.repetitions / self.duration)
		print "Successes  Probability  Cumulative"
		sxArray = range(0,self.drawCount + 1)
		sxArray.reverse()
		cumulative = 0
		for successes in sxArray:
			tier = self.results[successes]
			sxCount = tier['count']
			cumulative += sxCount
			others = []
			for result in tier.keys():
				if result != 'count':
					count = tier[result]
			  		percentage = (count * 100) / sxCount
			  		line = "%2d%% %s" % (percentage, result)
					others.append(line)
			others.sort(reverse = True)
			percentage = (sxCount * 100.0) / self.repetitions
			cumulativePercent = (cumulative * 100.0) / self.repetitions
			print "%5d %14.2f%% %10.2f%%  (%s)" % (successes,percentage,cumulativePercent,", ".join(others))
		print

# Set the number of tests made for each simulation. The higher the number, the more accurate 
# the result will be, but the longer the simulation will take.
repetitions=100000

# Each entry in this array will cause one simulation to run. Each entry contains settings that guide the simulation.
#  Field 1: The description of the simulation. This gets is printed in the first line of the results.
#  Field 2: The collection of stones. Item is a pair like "B":10, which means ten black stones. Each color
#           of stone must use a unique letter. Example: if you wanted 3 black and 2 white stones, enter
#           {"B":3,"W":2} in this field.
#  Field 3: (Optional) If provided, tells the simulation how many stones to draw with each test. Defaults to five.
#  Field 4: (Optional) A list of which colors are counted as successes. Defaults to ("B").
tests = [
	("Standard",{"B":10,"W":2,"C":2,"R":2}),
	("Standard, reds as success",{"B":10,"W":2,"C":2,"R":2},5,("B","R")),
	("Six black",{"B":6,"W":2,"C":2,"R":2}),
	("Six black, reds also success",{"B":6,"W":2,"C":2,"R":2},5,("B","R")),
	("Six black, reds and white also success",{"B":6,"W":2,"C":2,"R":2},5,("B","R","W")),
	("Nine black",{"B":9,"W":2,"C":2,"R":2}),
	("Eight black",{"B":8,"W":2,"C":2,"R":2}),
	("Seven black",{"B":7,"W":2,"C":2,"R":2}),
	("Six black",{"B":6,"W":2,"C":2,"R":2}),
	("Six black, draw four",{"B":6,"W":2,"C":2,"R":2},4),
	("Eleven black",{"B":11,"W":2,"C":2,"R":2}),
	("Half the stones",{"B":5,"W":1,"C":1,"R":1}),
	("1.5 times the stones",{"B":15,"W":3,"C":3,"R":3}),
	("Standard, drawing four",{"B":10,"W":2,"C":2,"R":2},4),
	("Half stones, drawing four",{"B":5,"W":1,"C":1,"R":1},4),
	("Half stones, drawing three",{"B":5,"W":1,"C":1,"R":1},3),
	("Standard, drawing six",{"B":10,"W":2,"C":2,"R":2},6),
	("Non-black in 3:2:1 ratio",{"B":10,"W":3,"C":2,"R":1}),
	("No clear",{"B":10,"W":2,"C":0,"R":2}),
	("Add two yellow",{"B":10,"W":2,"C":2,"R":2,"Y":2}),
	("Replace two black with yellow",{"B":8,"W":2,"C":2,"R":2,"Y":2})
]

for test in tests:
	description = test[0]
	stones = test[1]
	drawCount = 5
	successOn = ("B")
	try:
		drawCount = test[2]
		successOn = test[3]
	except:
		pass
	bag = Bag(stones)
	simulation = Simulation(description,bag,drawCount,successOn)
	simulation.run(repetitions)
	simulation.report()

