Latin squares

The overall problem is that you create constraints and then use bagof/findall to copy them. The all solutions predicates (or anything that copies terms) do not play too well with constraints. We can fix this using this implementation for finding the diagonals:

diagonals(Square,A,B) :-
    length(Square,N),
    numlist(1,N,Xs),
    maplist(matrix_diagonal_one(N, Square), Xs, A),
    maplist(matrix_diagonal_two(N, Square), Xs, B).

matrix_diagonal_one(_, Square, X, V) :-
    nth1(X, Square, Row),
    nth1(X, Row, V).
matrix_diagonal_two(N, Square, X, V) :-
    nth1(X, Square, Row),
    Y is N+1-X,
    nth1(Y, Row, V).

As maplist/4 doesn’t copy, the problem vanishes, just like creating the constraints after the copying. Functional programmers avoid the two helpers using yall :slight_smile:

6 Likes