Skip to content

Instantly share code, notes, and snippets.

@wrongu
Last active January 12, 2016 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrongu/56fba3bdd6c2a763eb6d to your computer and use it in GitHub Desktop.
Save wrongu/56fba3bdd6c2a763eb6d to your computer and use it in GitHub Desktop.
a python brute force solution to https://www.behance.net/gallery/32501799/Puzzlebot
class Constraint(object):
def __init__(self, guess, lights):
self.n = guess
self.l = lights
self.g = sum(1 if c is 'g' else 0 for c in lights)
self.r = sum(1 if c is 'r' else 0 for c in lights)
def consistent(self, m):
# given m as 'true', return true iff this constraint would have come about from m
in_place = [v[0]==v[1] for v in zip(m, self.n)]
# since in-place (green) has precedence, check it first and remove it from m and n
# (what's left is n_remain compared against m_remain)
n_remain = [v for (p,v) in zip(in_place, self.n) if not p]
m_remain = [v for (p,v) in zip(in_place, m) if not p]
# count number of out of place but correct numbers (i.e. caused red lights)
out_of_place = 0
for i,v in enumerate(n_remain):
if v in m_remain:
out_of_place += 1
m_remain[m_remain.index(v)] = -1 # must set to -1 so 00 cannot match twice to 01, e.g.
return sum(in_place) == self.g and out_of_place == self.r
if __name__ == '__main__':
import itertools
# init 'constraints' (previous guesses and the resulting lights)
guesses = [[2,5,4,9],[0,4,2,4],[3,8,1,6],[5,0,0,4]]
lights = ['g...', 'rrr.', '....', 'gr..']
constraints = [Constraint(guesses[i], lights[i]) for i in range(len(guesses))]
# init list of all possible 4-digit tuples
all_m = itertools.product(*([range(10)]*len(guesses[0])))
# filter down to only the tuples consistent with each constraint
for c in constraints:
filtered = [m for m in all_m if c.consistent(m)]
all_m = filtered
# print the result
print all_m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment