% priklad na reseni posunovacky pomoci A*

start([2/2, 3/1, 2/3, 2/1, 3/3, 1/2, 3/2, 1/3, 1/1]).

goal([1/3, 2/3, 3/3, 1/2, 2/2, 3/2, 1/1, 2/1, 3/1]).

% move pomoci pohybu mezery (cena vzdy 1)
move([XB/YB | Numbers], [XL/YB | NewNumbers], 1) :-
    XB>1, % pohyb mezery doleva
    XL is XB - 1, replace(XL/YB, XB/YB, Numbers, NewNumbers).
move([XB/YB | Numbers], [XR/YB | NewNumbers], 1) :-
    XB<3, % pohyb mezery doprava
    XR is XB + 1, replace(XR/YB, XB/YB, Numbers, NewNumbers).
move([XB/YB | Numbers], [XB/YD | NewNumbers], 1) :-
    YB>1, % pohyb mezery dolu
    YD is YB - 1, replace(XB/YD, XB/YB, Numbers, NewNumbers).
move([XB/YB | Numbers], [XB/YU | NewNumbers], 1) :-
    YB<3, % pohyb mezery nahoru
    YU is YB + 1, replace(XB/YU, XB/YB, Numbers, NewNumbers).

% replace

replace(A,B,[A|T],[B|T]):-!.
replace(A,B,[H|T1],[H|T2]) :- replace(A,B,T1,T2).

% heuristika h1
h(State,H):-
    cnt_1(State,Ok_1),
    cnt_2(State,Ok_2),
    cnt_3(State,Ok_3),
    cnt_4(State,Ok_4),
    cnt_5(State,Ok_5),
    cnt_6(State,Ok_6),
    cnt_7(State,Ok_7),
    cnt_8(State,Ok_8),
    H is Ok_1+Ok_2+Ok_3+Ok_4+Ok_5+Ok_6+Ok_7+Ok_8.
    %write('H['),write(State),write(']='),write(H),nl.

%goal([1/3, 2/3, 3/3, 1/2, 2/2, 3/2, 1/1, 2/1, 3/1]).
cnt_1([_,2/3|_],0):-!. cnt_1(_,1).
cnt_2([_,_,3/3|_],0):-!. cnt_2(_,1).
cnt_3([_,_,_,1/2|_],0):-!. cnt_3(_,1).
cnt_4([_,_,_,_,2/2|_],0):-!. cnt_4(_,1).
cnt_5([_,_,_,_,_,3/2|_],0):-!. cnt_5(_,1).
cnt_6([_,_,_,_,_,_,1/1|_],0):-!. cnt_6(_,1).
cnt_7([_,_,_,_,_,_,_,2/1|_],0):-!. cnt_7(_,1).
cnt_8([_,_,_,_,_,_,_,_,3/1],0):-!. cnt_8(_,1).

% 

biggest(99).
writelist(L):-writelist(L,1).
writelist([E|L],I):-write(I),write(': '),write(E),nl,I1 is I+1,writelist(L,I1).
writelist([],_).

run:- 
    ['4.1_9.pl'], nl,
    write('8-posunovacka, algoritmus A*, heuristika h1'), nl, nl,
    start(Start),
    write('Pocatecni stav: '), write(Start), nl,
    bestsearch(Start, Solution), 
    write('Nalezene reseni:'),nl,
    reverse(Solution,RSolution),
    writelist(RSolution).

% s heuristikou h1 vyzaduje hodne pameti (pro d=26)
:- set_prolog_stack(local,  limit(256 000 000)). % vyzaduje 64-bit system
:- run.

% vim: set ft=prolog:
