Skip to content

Instantly share code, notes, and snippets.

@joshuashaffer
Last active April 24, 2018 20:28
Show Gist options
  • Save joshuashaffer/26ab46411feadabe3099338b3ad46f9f to your computer and use it in GitHub Desktop.
Save joshuashaffer/26ab46411feadabe3099338b3ad46f9f to your computer and use it in GitHub Desktop.
Online master mind solver
import attr
@attr.s(frozen=True, slots=True)
class T(object):
a = attr.ib(default=1, type=int)
b = attr.ib(default=1, type=int)
c = attr.ib(default=1, type=int)
d = attr.ib(default=1, type=int)
perfect = attr.ib(default=1, type=int)
misses = attr.ib(default=1, type=int)
def score(trial, target):
a = attr.astuple(trial)[:4]
b = attr.astuple(target)[:4]
perfect = sum(map(lambda x: int(x[0] == x[1]), zip(a, b)))
misses = sum(int(x not in b) for x in a)
return perfect, misses
def unique(trial):
return len(set(attr.astuple(trial)[:4]))
if __name__ == "__main__":
guesses = []
round = 1
while True:
print("round {} {}".format(round, "-" * 80))
guesses.append(T(a=int(input('a? ')),
b=int(input('b? ')),
c=int(input('c? ')),
d=int(input('d? ')),
perfect=int(input('perfect? ')),
misses=int(input('misses? '))))
sols = []
for a in range(1, 7):
for b in range(1, 7):
for c in range(1, 7):
for d in range(1, 7):
sat = True
t = T(a=a, b=b, c=c, d=d)
for x in guesses:
p, m = score(x, t)
if p != x.perfect or m != x.misses:
sat = False
if sat:
sols.append(t)
if (len(sols) == 0):
print("No Solution")
break
sols = sorted(sols, key=unique, reverse=True)
attr_astuple = map(str, list(attr.astuple(sols[0])[:4]))
print("Try Code: {}".format(''.join(attr_astuple)))
if len(sols) < 2:
break
round += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment