9589 AI Exp6
9589 AI Exp6
Artificial Intelligence
Total
Signature of the Teacher
AI EXPERIMENT 6
CODE:
target( [[ 1 , 2 , 3],
[ 4 , 5 , 6],
[ 7 , 8 , _]] ).
% new_hole_position(Row,Col,RowNew,ColNew,MoveDirection)
pick_and_put_matrix(Row,Col,MatrixIn,ValOld,ValNew,MatrixOut) :-
pick_and_put(Row,MatrixIn,RowlistOld,RowlistNew,MatrixOut),
pick_and_put(Col,RowlistOld,ValOld,ValNew,RowlistNew).
pick_and_put(Index,ListIn,ValOld,ValNew,ListOut) :-
length(Prefix,Index), append([Prefix,[ValOld],Suffix],ListIn),
append([Prefix,[ValNew],Suffix],ListOut),
!.
cur_hole_position(Row,Col,MatrixIn) :-
nth0(Row,MatrixIn,RowList),
cur_hole_position_in_row(Col,RowList),!.
cur_hole_position_in_row(Col,RowList) :-
nth0(Col,RowList,[]).
nb_inc_counter :-
nb_getval(counter,X), XX
is X+1,
nb_setval(counter,XX).
% The search proper. Perform a single move from one state (matrix)
% to the next state (matrix)
%
% move(+CurrentState,+GoalState,
% -SolutionAsGrowingOpenListToWhichOneAppends
% +StatesOnPathSoAsToNotVisitAStateTwiceToWhichOnePrepends,
% +DepthCountdownForIterativeDeepening)
move(Matrix,Matrix,[],_,_) :- !.
move(MatrixIn,MatrixTarget,[MatrixMid|Moves],MatrixesOnPath,Depth)
:-
Depth > 1,
nb_inc_counter,
cur_hole_position(Row,Col,MatrixIn),
new_hole_position(Row,Col,RowNew,ColNew,_MoveDirection),
move_hole(Row,Col,RowNew,ColNew,MatrixIn,MatrixMid),
\+ member(MatrixMid,MatrixesOnPath),
SmallerDepth is Depth-1,
move(MatrixMid,MatrixTarget,Moves,[MatrixMid|MatrixesOnPath],Small
erDepth).
% Printout curclicues
print_and_reset_counter :-
nb_getval(counter,C), (C>0
-> format("Examined ~d positions~n",[C])
; true),
nb_setval(counter,0).
format_moves([Matrix],_) :-
format_matrix(Matrix).
format_moves([Matrix,Matrix2|Moves],Index) :-
format_matrix(Matrix), format("Move
~d~n",[Index]), Index2 is Index+1,
format_moves([Matrix2|Moves],Index2).
format_matrix([[A,B,C],[D,E,F],[G,H,I]]) :-
enlarge(A,AE), enlarge(B,BE),
enlarge(C,CE), enlarge(D,DE),
enlarge(E,EE), enlarge(F,FE),
enlarge(G,GE), enlarge(H,HE),
enlarge(I,IE), format("+--------+~n",[]),
format("|~s,~s,~s|~n",[AE,BE,CE]),
format("|~s,~s,~s|~n",[DE,EE,FE]),
format("|~s,~s,~s|~n",[GE,HE,IE]),
format("+--------+~n",[]).
enlarge(X,XE) :-
format(string(S)," ~q",[X]),
sub_string(S,_,2,0,XE).
% "Main" predicate.
run(Moves) :-
from(MatrixFrom),
target(MatrixTarget),
nb_setval(counter,0),
between(1,30,MaxDepth), % backtrackable; iterative deepening
print_and_reset_counter,
format("Maximum depth is ~d~n",[MaxDepth]),
move(MatrixFrom,MatrixTarget,Moves,[MatrixFrom],MaxDepth),
announce_success([MatrixFrom|Moves]).
announce_success(Moves) :-
length(Moves,Length), AdjustedLength is Length-
1, nb_getval(counter,C),
format("Found a solution of ~d moves by examination of ~d
positions.~n",[AdjustedLength,C]),
format_moves(Moves,1)
OUTPUT: