1

我必须制作一个解决难题 8 的序言程序。这是为了我在学校的编程俱乐部,我只是为了好玩。我是 Prolog 的新手——我很难过。这是我的代码:

puzzle([1, 2, 3, 4, 5, 6, 7, 8, 0]).

%%up
c([0, X2, X3, X4, X5, X6, X7, X8, X9], [X4, X2, X3, 0, X5, X6, X7, X8, X9]).
c([X1, 0, X3, X4, X5, X6, X7, X8, X9], [X1, X5, X3, X4, 0, X6, X7, X8, X9]).
c([X1, X2, 0, X4, X5, X6, X7, X8, X9], [X1, X2, X6, X4, X5, 0, X7, X8, X9]).
c([X1, X2, X3, 0, X5, X6, X7, X8, X9], [X1, X2, X3, X7, X5, X6, 0, X8, X9]).
c([X1, X2, X3, X4, 0, X6, X7, X8, X9], [X1, X2, X3, X4, X8, X6, X7, 0, X9]).
c([X1, X2, X3, X4, X5, 0, X7, X8, X9], [X1, X2, X3, X4, X5, X9, X7, X8, 0]).

%%right
d([0, X2, X3, X4, X5, X6, X7, X8, X9], [X2, 0, X3, X4, X5, X6, X7, X8, X9]).
d([X1, 0, X3, X4, X5, X6, X7, X8, X9], [X1, X3, 0, X4, X5, X6, X7, X8, X9]).
d([X1, X2, X3, 0, X5, X6, X7, X8, X9], [X1, X2, X3, X5, 0, X6, X7, X8, X9]).
d([X1, X2, X3, X4, 0, X6, X7, X8, X9], [X1, X2, X3, X4, X6, 0, X7, X8, X9]).
d([X1, X2, X3, X4, X5, X6, 0, X8, X9], [X1, X2, X3, X4, X5, X6, X8, 0, X9]).
d([X1, X2, X3, X4, X5, X6, X7, 0, X9], [X1, X2, X3, X4, X5, X6, X7, X9, 0]).

%%down
b([X1, X2, X3, 0, X5, X6, X7, X8, X9], [0, X2, X3, X1, X5, X6, X7, X8, X9]).
b([X1, X2, X3, X4, 0, X6, X7, X8, X9], [X1, 0, X3, X4, X2, X6, X7, X8, X9]).
b([X1, X2, X3, X4, X5, 0, X7, X8, X9], [X1, X2, 0, X4, X5, X3, X7, X8, X9]).
b([X1, X2, X3, X4, X5, X6, 0, X8, X9], [X1, X2, X3, 0, X5, X6, X4, X8, X9]).
b([X1, X2, X3, X4, X5, X6, X7, 0, X9], [X1, X2, X3, X4, 0, X6, X7, X5, X9]).
b([X1, X2, X3, X4, X5, X6, X7, X8, 0], [X1, X2, X3, X4, X5, 0, X7, X8, X6]).

%%left
e([X1, 0, X3, X4, X5, X6, X7, X8, X9], [0, X1, X3, X4, X5, X6, X7, X8, X9]).
e([X1, X2, 0, X4, X5, X6, X7, X8, X9], [X1, 0, X2, X4, X5, X6, X7, X8, X9]).
e([X1, X2, X3, 0, X5, X6, X7, X8, X9], [X1, X2, X3, X5, 0, X6, X7, X8, X9]).
e([X1, X2, X3, X4, 0, X6, X7, X8, X9], [X1, X2, X3, X4, X6, 0, X7, X8, X9]).
e([X1, X2, X3, X4, X5, X6, 0, X8, X9], [X1, X2, X3, X4, X5, X6, X8, 0, X9]).
e([X1, X2, X3, X4, X5, X6, X7, 0, X9], [X1, X2, X3, X4, X5, X6, X7, X9, 0]).

%%prints puzzle
affiche_puzzle :-
    puzzle(Puzzle),
    printe(Puzzle).
printe([]).
printe([H1,H2,H3|Puzzle]) :-
    format('~w ~w ~w~n', [H1, H2, H3]),
    printe(Puzzle).

现在我必须创建 mov_legal(C1, M, P, C2) --> c2 是从配置 c1 中获得的,移动 M,移动块 P。这是一个预期的结果:

?- mov_legal([1, 2, 3, 4, 5, 0, 7, 8, 6], M, P, C).
M = c,
P = 6,
C = [1, 2, 3, 4, 5, 6, 7, 8, 0] ;
M = b,
P = 3,
C = [1, 2, 0, 4, 5, 3, 7, 8, 6] ;
...

如果您能帮助我,我将不胜感激!

4

1 回答 1

0

我希望更改配置的谓词:

%%up
legal_move([0, X2, X3, X4, X5, X6, X7, X8, X9], c, 4, [X4, X2, X3, 0, X5, X6, X7, X8, X9]). 
legal_move([X1, 0, X3, X4, X5, X6, X7, X8, X9], c, 5, [X1, X5, X3, X4, 0, X6, X7, X8, X9]).
...

尽管如果您不想或出于任何原因不能这样做,您可以执行以下操作:

legal_move(C1,c,C2) :- c(C1,C2). %% left
legal_move(C1,d,C2) :- d(C1,C2). %% right
legal_move(C1,b,C2) :- b(C1,C2). %% down
legal_move(C1,e,C2) :- e(C1,C2). %% up
legal_move(C1,C,P,C2) :- legal_move(C1,C,C2), nth1(P,C2,0).

以防万一你没有注意到。您还在配置中犯了一些复制粘贴错误。(你的左谓词部分错误)

于 2015-12-16T20:20:47.247 回答