Advertisement
girinovey

mensaMastermind.py

Jan 12th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1. from itertools import combinations, product
  2.  
  3. def matches(inp, comp, num_exact_pos, num_wrong_pos):
  4.     count_exact = sum([inp[i] == comp[i] for i in xrange(len(inp))])
  5.     count_inexact = len(set(inp).intersection(set(comp))) - count_exact
  6.     return count_exact == num_exact_pos and count_inexact == num_wrong_pos
  7.  
  8. def matches_all(code, rules):
  9.     return all([matches(code, y[0], y[1], y[2]) for y in rules])
  10.  
  11. # rules are composed of a guessed value, the number of exact matches, and the number of matches in wrong places
  12. all_rules = [
  13.          [[6,8,2], 1, 0],
  14.          [[6,1,4], 0, 1],
  15.          [[2,0,6], 0, 2],
  16.          [[7,3,8], 0, 0],
  17.          [[7,8,0], 0 ,1]
  18.         ]
  19. # add numbering
  20. all_rules = [all_rules[i] + [i+1] for i in xrange(len(all_rules))]
  21.  
  22. # examines all combinations of rules
  23. for i in xrange(len(all_rules)):
  24.     for rules in combinations(all_rules, i+1):
  25.         results = [code for code in product(range(10), repeat=len(rules[0][0])) if matches_all(code, rules)]
  26.         rule_nums = [x[3] for x in rules]
  27.         if len(results) == 0:
  28.             print "rules" , rule_nums, "are contradictory"
  29.         elif len(results) == 1:
  30.             print "rules" , rule_nums, "are suficient,", "result =", "".join(map(str,results[0]))
  31.         else:
  32.             print "rules" , rule_nums, "are insuficient,", len(results), "matches found"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement