0

I'm trying to resolve chess knight problem for custom matrix but I don't know where is problem. A chess knight must visit each place once, and when he manages to visit all fields then finish the program. Currently, he is looking for the correct combination of fields all the time and it takes a very long time ... I have no idea what to do next or what to change

append([], POINT, [POINT]).
append([H|T], POINT, [H|R]) :- 
    append(T, POINT, R).

member(POINT,[POINT|_]).
member(POINT,[_|R]) :- 
    member(POINT, R).

try(X, Y, Xmax, Ymax, A, B) :- 
    (X + 1 < Xmax, Y + 2 < Ymax, A is X + 1, B is Y + 2).
try(X, Y, Xmax, Ymax, A, B) :- 
    (X + 2 < Xmax, Y + 1 < Ymax, A is X + 2, B is Y + 1).
try(X, Y, Xmax, Ymax, A, B) :- 
    (X + 2 < Xmax, Y - 1 >= Ymax - Ymax, A is X + 2, B is Y - 1).
try(X, Y, Xmax, Ymax, A, B) :- 
    (X + 1 < Xmax, Y - 2 >= Ymax - Ymax, A is X + 1, B is Y - 2).
try(X, Y, Xmax, Ymax, A, B) :-  
    (X - 1 >= Xmax - Xmax, Y - 2 >= Ymax - Ymax, A is X - 1, B is Y - 2).
try(X, Y, Xmax, Ymax, A, B) :- 
    (X - 2 >= Xmax - Xmax, Y - 1 >= Ymax- Ymax, A is X - 2, B is Y - 1).
try(X, Y, Xmax, Ymax, A, B) :-  
    (X - 2 >= Xmax - Xmax, Y + 1 < Ymax, A is X - 2, B is Y + 1).
try(X, Y, Xmax, Ymax, A, B) :- 
    (X - 1 >= Xmax - Xmax, Y + 2 < Ymax, A is X - 1, B is Y + 2).


move(X, Y, Xmax, Ymax, L) :-
    not(member([X, Y], L)),
    write('X='), write(X),
    write('Y='), write(Y), nl,
    try(X, Y, Xmax, Ymax, A, B),
    append(L, [X, Y], L2),
    move(A, B, Xmax, Ymax, L2).

Example:move(0, 0, 3, 3, []).

Output

X=0Y=0
X=1Y=2
X=2Y=0
X=0Y=1
X=2Y=2
X=1Y=0
X=0Y=2
X=2Y=1
X=2Y=1
X=0Y=2
X=1Y=0
X=2Y=2
X=0Y=1
X=2Y=0
X=1Y=2
false

That's true, because it will never be in the center of the matrix. But for matrix 5x5 he can't find combination...

Sekru
  • 515
  • 2
  • 11

1 Answers1

0

New attempt. This code:

move(X,Y,Xmax,Ymax,L) :-
  ( try(X,Y,Xmax,Ymax,A,B), not(member([A,B],L)) ->
    write('X='), write(A), write(' '), write('Y='), write(B), nl,
    append(L,[A,B],L2),
    move(A,B,Xmax,Ymax,L2)
  ; true ).

Gives me (for move(0,4,5,5,[])):

X=2 Y=3
X=4 Y=4
X=3 Y=2
X=4 Y=0
X=2 Y=1
X=3 Y=3
X=4 Y=1
X=2 Y=0
X=0 Y=1
X=1 Y=3
X=3 Y=4
X=4 Y=2
X=3 Y=0
X=1 Y=1
X=0 Y=3
X=2 Y=4
X=4 Y=3
X=3 Y=1
X=1 Y=0
X=2 Y=2
X=1 Y=4
X=0 Y=2

Is this not what you were expecting?

Tomas By
  • 1,396
  • 1
  • 11
  • 23