Advertisement
here2share

# mastermind_solver.py

Nov 13th, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. # mastermind_solver.py
  2.  
  3. import random
  4. from sets import Set
  5.  
  6. # traditional Mastermind uses six different colors, not exactly certain
  7. # what they were, so I chose Red/Yellow/Blue/Orange/Green/Purple...
  8.  
  9. colors = ['R', 'Y', 'B', 'O', 'G', 'P']
  10.  
  11.  
  12. # generate a random secret code (or guess)
  13.  
  14. def randomcode():
  15.         return ''.join([random.choice(colors) for i in range(4)])
  16.  
  17. def evaluate(guess, secret):
  18.         b, w = 0, 0
  19.         gs, ss = Set([]), Set([])
  20.         for i in range(4):
  21.             if guess[i] == secret[i]:
  22.                 b = b + 1
  23.             else:
  24.                 gs.add(guess[i])
  25.                 ss.add(secret[i])
  26.         return b, len(gs.intersection(ss))
  27.  
  28. def solve(secret):
  29.         history = []
  30.         guess = randomcode()
  31.         nguesses = 1
  32.         while True:
  33.                 b, w = evaluate(guess, secret)
  34.                 history.append((guess, b, w))
  35.                 print guess, b, w
  36.                 if b == 4:
  37.                         break   # we solved it...
  38.                 # generate a new random guess, consistent with
  39.                 # all the previous guesses.
  40.                 nguesses = nguesses + 1
  41.                 while True:
  42.                         guess = randomcode()
  43.                         consistent = True
  44.                         for g, b, w in history:
  45.                                 nb, nw = evaluate(guess, g)
  46.                                 if nb != b or nw != w:
  47.                                         # nope, not consistent
  48.                                         consistent=False
  49.                                         break
  50.                         if consistent:
  51.                                 break
  52.         print
  53.         return nguesses
  54.  
  55. ROUNDS = 100
  56. totalguesses = 0
  57.  
  58. for x in range(ROUNDS):
  59.         totalguesses = totalguesses + solve(randomcode())
  60.  
  61. print "average number of guesses was %.2f" % (float(totalguesses)/ROUNDS)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement