Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # mastermind_solver.py
- import random
- from sets import Set
- # traditional Mastermind uses six different colors, not exactly certain
- # what they were, so I chose Red/Yellow/Blue/Orange/Green/Purple...
- colors = ['R', 'Y', 'B', 'O', 'G', 'P']
- # generate a random secret code (or guess)
- def randomcode():
- return ''.join([random.choice(colors) for i in range(4)])
- def evaluate(guess, secret):
- b, w = 0, 0
- gs, ss = Set([]), Set([])
- for i in range(4):
- if guess[i] == secret[i]:
- b = b + 1
- else:
- gs.add(guess[i])
- ss.add(secret[i])
- return b, len(gs.intersection(ss))
- def solve(secret):
- history = []
- guess = randomcode()
- nguesses = 1
- while True:
- b, w = evaluate(guess, secret)
- history.append((guess, b, w))
- print guess, b, w
- if b == 4:
- break # we solved it...
- # generate a new random guess, consistent with
- # all the previous guesses.
- nguesses = nguesses + 1
- while True:
- guess = randomcode()
- consistent = True
- for g, b, w in history:
- nb, nw = evaluate(guess, g)
- if nb != b or nw != w:
- # nope, not consistent
- consistent=False
- break
- if consistent:
- break
- print
- return nguesses
- ROUNDS = 100
- totalguesses = 0
- for x in range(ROUNDS):
- totalguesses = totalguesses + solve(randomcode())
- print "average number of guesses was %.2f" % (float(totalguesses)/ROUNDS)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement