def solveBoard(board): global numUnique, printResult, checkUnique, checkUnique def assumeBoard(printBoard): for v in checkAssumps: cnf.assume(-v) row = 0 col = 0 for b in board: if printBoard: sys.stdout.write(b) if b == ".": pass else: i = -1 if N < 10: i = int(b) - 1 else: i = ord(b) - ord("A") # print '(%d,%d) = i = %d' % (row,col,i) cnf.assume(p[i][row][col]) col += 1 if col == N: col = 0 row += 1 if row == N: break if printBoard: sys.stdout.write("\n") assumeBoard(printResult) result = cnf.solve() assert result == cnf.RESULT_SAT if printResult: showBoard(board) if checkUnique: v = cnf.newVar("uniq") c = [-v] for j in range(0, N): for k in range(0, N): for i in range(0, N): if cnf.assignment(p[i][j][k]): c.append(-p[i][j][k]) cnf.addClause("uniq", c) assumeBoard(False) cnf.assume(v) checkAssumps.append(v) result = cnf.solve() if result == cnf.RESULT_SAT: print "non-unique board" showBoard(board) return False elif result == cnf.RESULT_UNSAT: numUnique += 1 return True
# - The baker who made oatmeal raisin cookies doesn't have the Congolese penpal. for n in names: cnf.addClause([ -cn.entry(n, 'oatmealraisin'), pn.entry(n, 'congolese') ]) # - The employee with the $188,000 salary didn't bake black and white cookies. for n in names: cnf.addClause([ -sn.entry(n, 188000), -cn.entry(n, 'blackwhite') ]) # - Either the baker who made oatmeal raisin cookies or the baker who made # - peanut butter cookies is Valerie. cnf.addClause([ cn.entry('oatmealraisin', 'valerie'), cn.entry('peanutbutter', 'valerie') ]) # - Of the baker who made peanut butter cookies and Braxton, one earns $86,000 # - per year and the other has the Uruguayan penpal. for n in names: pn.entry(n, 'uruguayan') sc.entry(86000, 'peanutbutter') sn.entry(86000, 'braxton') pn.entry('braxton', 'uruguayan') # - The employee with the $86,000 salary has the Panamanian penpal. result = cnf.solve() print result