# Encoding lparse encoding

Name lparse encoding [Root]    Puzzles (51)    NumberSquares (4) Martin Gebser lparse encoding of Putting Numbers 2009-03-30 13:03 2008-11-29 00:10 No % generate_number_square_normal.lp -- a smodels program for creating % number squares. %% First define the four possible directions of the numbers. The %% second and the third argument give the direction vector and they %% are used to make the following encoding more readable. dir(n, 0, 1). dir(e, 1, 0). dir(s, 0, -1). dir(w, -1, 0). %% Define a new atom for every different number in the input. num(N) :- number(N, Pos, B). %% Each symbol may occur in any square of the grid. { grid(X, Y, S) : symbol(S) } :- square(X, Y). %% It is an error if there are two different numbers on the same %% position: :- 2 { grid(X, Y, S) : symbol(S) }, square(X, Y). %% Since we know the length of all input numbers, we don't want to %% search them from places where they do not fit in. A number doesn't %% fit in a position if it extends out of the square. impossible_place(N, X, Y, Dir) :- number(N, Pos, B_1), square(X, Y), dir(Dir, X_d, Y_d), not square(X + Pos * X_d, Y + Pos * Y_d). %% A square is a possible place for the number if it is not %% impossible. possible_place(N, X, Y, Dir) :- not impossible_place(N, X, Y, Dir), num(N), square(X, Y), dir(Dir, X_d, Y_d). %% Next, a number is at a place if it fits in there and all its digits %% are in the correct place: at(N, X, Y, Dir) :- ok_num(N, Pos, X, Y, Dir) : number(N, Pos, B), possible_place(N, X, Y, Dir). %% A the "Pos"th digit of the number is correct if it occurs in the %% grid at the correct position. ok_num(N, Pos, X, Y, Dir) :- number(N, Pos, B_1), possible_place(N, X, Y, Dir), grid(X + Pos * X_d, Y + Pos * Y_d, B_1), dir(Dir, X_d, Y_d). %% We have placed a number if it occurs somewhere: found(N) :- at(N, X, Y, Dir), possible_place(N, X, Y, Dir). %% It is an error if some number has not been found: :- num(N), not found(N).