开发者

Find duplicates in the same row and column in a grid using Prolog

I am new to Prolog. I am writing Prolog code to solve a puzzle which requires me to find duplicates in a 2 dimensional grid of numbers.

My input is something like:

grid(1,1,1).
grid(2,1,2).
grid(2,1,3).
grid(5,1,4).
grid(3,2,1).
grid(4,2,2).
grid(5,2,开发者_JS百科3).
grid(9,2,4).
grid(6,3,1).
grid(7,3,2).
grid(2,3,3).
grid(8,3,4).
grid(4,4,1).
grid(5,4,2).
grid(1,4,3).
grid(3,4,4).

which represents the matrix:

1 2 2 5
3 4 5 9
6 7 2 8
4 5 1 3

The code I was trying was something like:

finddup(N,X,Y):-
        a is X, b is Y,
        print('Rule 1 \n'),
        ((grid(N,U,1), U \= a, print('U->'), write(U), print('\n'), print('X->'), write(a));
        (grid(N,1,U), U \= b, print('U->'), write(U), print('\n'), print('Y->'), write(b));
        (grid(N,U,4), U \= a, print('U->'), write(U), print('\n'), print('X->'), write(a));
        grid(N,4,U), U \= b, print('U->'), write(U), print('\n'), print('Y->'), write(b)));
        print('Rule 2 \n'),
        ((finddup(N,X-1,Y), X-1 >= 1, X-1 =< 4, Y >= 1, Y =< 4);
        (finddup(N,X+1,Y), X+1 >= 1, X+1 =< 4, Y >= 1, Y =< 4);
        (finddup(N,X,Y-1), X >= 1, X =< 4, Y-1 >= 1, Y-1 =< 4);
        (finddup(N,X,Y+1), X >= 1, X =< 4, Y+1 >= 1, Y+1 =< 4)).

Please help me out guys ... I have been trying this since a week or two ...

Thanks,

Vikas


You don't need to try and specify the ranges of the row and column indices since they are already explicitly given in the grid(..) facts. Just let Prolog backtrack over the values.

finddup(N,R,C) :-
    grid(N,R,C),
    grid(N,R,C2), C \= C2,
    grid(N,R2,C), R \= R2.

grid(N,R,C) will verify that the given values are in the grid, or it will backtrack over all the possible combinations if any (or all) of N, R, C have no values.

grid(N,R,C2), C \= C2, will find another column in the same row that has the same N.

Likewise for grid(N,R2,C), R \= R2 - but for another row.

This will return a true for any duplicate it finds, but will probably return a false after that, since the last backtrack may fail. For example:

?- finddup(N,R,C).
N = 2,
R = 1,
C = 3 ;
false.

?- finddup(2,1,3).
true ;
false.

?- 

(where the semicolons are user input)

You can add a cut at the end to stop any further backtracking once a solution has been found:

finddup(N,R,C) :-
    grid(N,R,C),
    grid(N,R,C2), C \= C2,
    grid(N,R2,C), R \= R2, !.

gives

?- finddup(N,R,C).
N = 2,
R = 1,
C = 3.

?- finddup(2,1,3).
true.

?- 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜