In [5]:
import Numberjack

SIZE = 8
grid = Numberjack.Matrix(SIZE, SIZE, 'grid')
model = Numberjack.Model()

# Two in each row/column.
for n in range(SIZE):
  model.add(
    Numberjack.Sum([grid[n][i] for i in range(SIZE)]) == 2,
    Numberjack.Sum([grid[i][n] for i in range(SIZE)]) == 2,
  )

def if_then(cond, then):
  return cond - then <= 0

def no_neighbors(grid, x, y):
  neighbors = []
  for dx in (-1, 0, 1):
    for dy in (-1, 0, 1):
      if ((0 <= x + dx < SIZE) and
          (0 <= y + dy < SIZE) and
          not (dx == 0 and dy == 0)):
        neighbors.append(grid[x + dx][y + dy])
  return Numberjack.Sum(neighbors) == 0

# May not touch.
for x in range(SIZE):
  for y in range(SIZE):
    model.add(if_then(grid[x][y], no_neighbors(grid, x, y)))
  
# TODO: Constrain column 2.
# for row in range(0, 3):
#   for col in range(0, 3):
#     model.add(
#         # Ones digit equals target...
#         (grid[row][col] % 10 == targets[row][col]) |
#         # Tens digit equals target...
#         (grid[row][col] - grid[row][col] % 10 == targets[row][col] * 10)
#     )
# (Not needed.)

# Solve.
solver = model.load('Mistral')
print('Solution is...')
solver.solve()
for row in range(0, SIZE):
  print(grid[row])

print('Nodes:', solver.getNodes(), ' Time:', solver.getTime())


Solution is...
[0, 0, 0, 0, 1, 0, 1, 0]
[1, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 1, 0]
[1, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 1]
[0, 1, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 1]
[0, 1, 0, 1, 0, 0, 0, 0]
Nodes: 790  Time: 0.029999999999999805

In [6]:
# Print mirrored solution.
soln = [
[0, 0, 0, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0],
]

for row in soln:
  print(list(reversed(row)))


[0, 1, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 1]
[0, 1, 0, 1, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 1, 0, 1]
[1, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 1, 0]
[1, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 1, 0]

In [ ]: