or-toolscp-sat

Self referencing constraints


In the process of familiarizing myself with the or-tools library from google. I've been implementing some simple examples. One exercise I set myself to do was to implement a sudoku solver. It was relatively simple to implement:

After that I came across a sudoku variant with some different rules and I tried to create a solver for this case but to no avail. I'm having a hard time implementing the constraints for the following rule:

When digit z is in cell (x, y) then digit y is in cell (x, z) and digit x is in cell (z, y)

I need to use the value of one of the cells in the sudoku board as one coordinate to another cell.

I have tried using the AddElement method:

size=9
# build board
board=[]
for i in range(size):
   row=[]
   for j in range(size):
      row.append(model.NewIntVar(1, 9, f"{i},{j}"))
   board.append(row)

# when digit z is in cell (x,y) then digit y is in cell (x,z) and digit x is in cell (z,y)
flat_board = [col for row in board for col in row]
for x in range(size):
    for y in range(size):
       z = model.NewIntVar(0,8,f"z{x}{y}")
       model.Add(z == board[x][y]-1)
       model.AddElement(x*size+z,flat_board, y+1)
       model.AddElement(z*size+y,flat_board, x+1)

I get this error: TypeError: NotSupported: model.GetOrMakeIndex((9 * z00))

Is this even possible to implement? If not AddElement, which method should I use?

Note: I'm using the python wrapper


Solution

  • The element constraint takes a variable for its index, not an arbitrary expression.