root/trunk/examples/searching/eight_puzzle.lgt

Revision 4601, 1.8 KB (checked in by pmoura, 7 weeks ago)

Added svn:mime-type property to source files (set to text/x-logtalk).

  • Property svn:mime-type set to text/x-logtalk
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1
2:- object(eight_puzzle,
3    instantiates(heuristic_state_space)).
4
5
6    :- info([
7        version is 1.1,
8        author is 'Paulo Moura',
9        date is 2004/8/15,
10        comment is 'Eight puzzle heuristic state space search problem.']).
11
12
13    :- uses(list, [member/2]).
14
15
16    initial_state(four_steps, [2/2,1/3,3/2,2/3,3/3,3/1,2/1,1/1,1/2]).
17
18    initial_state(five_steps, [2/1,1/2,1/3,3/3,3/2,3/1,2/2,1/1,2/3]).
19
20    initial_state(eighteen_steps, [2/2,2/3,1/3,3/1,1/2,2/1,3/3,1/1,3/2]).
21
22
23    goal_state(goal, [2/2,1/3,2/3,3/3,3/2,3/1,2/1,1/1,1/2]).
24
25
26    print_state([S0,S1,S2,S3,S4,S5,S6,S7,S8]) :-
27        member(Y, [3, 2, 1]),
28        nl,
29        member(X, [1, 2, 3]),
30        member(Tile-X/Y, [' '-S0,1-S1,2-S2,3-S3,4-S4,5-S5,6-S6,7-S7,8-S8]),
31        write(Tile),
32        fail.
33
34    print_state(_) :-
35        nl.
36
37
38    next_state([Empty| L], [Tile| L2], 1) :-
39        swap(Empty, Tile, L, L2).
40
41
42    swap(Empty, Tile, [Tile| L], [Empty| L]) :-
43        dist(Empty, Tile, 1).
44
45    swap(Empty, Tile, [Tile2| L], [Tile2| L2]) :-
46        swap(Empty, Tile, L, L2).
47
48
49    dist(X/Y, X2/Y2, D) :-
50        abs_diff(X, X2, Dx),
51        abs_diff(Y, Y2, Dy),
52        D is Dx + Dy.
53
54
55    abs_diff(A, B, D) :-
56        A > B ->
57            D is A - B
58            ;
59            D is B - A.
60
61
62    heuristic([_| L], H) :-
63        goal_state(_, [_| G]),
64        totdist(L, G, 0, D),
65        seq(L, S),
66        H is D + 3*S.
67
68
69    totdist([], [], D, D).
70
71    totdist([T| L], [T2| L2], Acc, D) :-
72        dist(T, T2, D1),
73        Acc2 is Acc + D1,
74        totdist(L, L2, Acc2, D).
75
76
77    seq([First| L], S) :-
78        seq([First| L], First, 0, S).
79
80
81    seq([T1, T2| L], First, Acc, S) :-
82        score(T1, T2, S1),
83        Acc2 is Acc + S1,
84        seq([T2| L], First, Acc2, S).
85
86    seq([Last], First, Acc, S) :-
87        score(Last, First, Score),
88        S is Acc + Score.
89
90
91    score(2/2, _, 1) :- !.
92
93    score(1/3, 2/3, 0) :- !.
94    score(2/3, 3/3, 0) :- !.
95    score(3/3, 3/2, 0) :- !.
96    score(3/2, 3/1, 0) :- !.
97    score(3/1, 2/1, 0) :- !.
98    score(2/1, 1/1, 0) :- !.
99    score(1/1, 1/2, 0) :- !.
100    score(1/2, 1/3, 0) :- !.
101
102    score(_, _, 2) :- !.
103
104
105:- end_object.
Note: See TracBrowser for help on using the browser.