Last active
March 5, 2019 11:57
-
-
Save jskripsky/8a32a82813dbfba95f04a01897e5c83a to your computer and use it in GitHub Desktop.
15 puzzle solver written in Prolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:- use_rendering(table). | |
next_to(X, Y) :- Y is X+1. | |
next_to(X, Y) :- Y is X-1. | |
neighbor(X, Y1, X, Y2) :- next_to(Y1, Y2). | |
neighbor(X1, Y, X2, Y) :- next_to(X1, X2). | |
tile(B, X, Y, N) :- | |
nth0(Y, B, R), | |
nth0(X, R, N). | |
set([_|T], 0, N, [N|T]). | |
set([H|T1], I, N, [H|T2]) :- | |
J is I-1, | |
set(T1, J, N, T2). | |
set(B1, X, Y, N, B2) :- | |
nth0(Y, B1, R1), | |
set(R1, X, N, R2), | |
set(B1, Y, R2, B2). | |
move(N, B1, B2) :- | |
tile(B1, X1, Y1, N), | |
tile(B1, X2, Y2, ' '), | |
neighbor(X1, Y1, X2, Y2), | |
set(B1, X1, Y1, ' ', C), | |
set(C, X2, Y2, N, B2). | |
moves([], B, B, _). | |
moves([N|Ns], B1, Bn, Max) :- | |
Max>0, move(N, B1, B2), | |
NewMax is Max-1, | |
moves(Ns, B2, Bn, NewMax). | |
shortest(Ns, B1, Bn) :- | |
length(Ns, L), moves(Ns, B1, Bn, L), | |
Max is L-1, \+moves(_, B1, Bn, Max). | |
scrambled3([[1,5,2],[7,' ',3],[8,4,6]]). | |
ordered3([[1,2,3],[4,5,6],[7,8,' ']]). | |
scrambled4([[2,3,7,4],[1,5,' ', 8],[9,6,10,11],[13,14,15,12]]). | |
ordered4([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,' ']]). | |
/** <examples> | |
?- scrambled3(S), ordered3(O), shortest(Moves,S,O). | |
?- scrambled4(S), ordered4(O), shortest(Moves,S,O). | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment