Home > Uncategorized > The Wolf, the Goat and the Cabbage (Salad) revisited; prolog version

The Wolf, the Goat and the Cabbage (Salad) revisited; prolog version

Prolog is nice for puzzle solving. This is my prolog solver.

:- use_module(library(lists)).

solve(S) :- mover([goat,wolf,salad],[],[],S).

mover(L,R,B,S) :-
    append(L,B,L1),
    member(X,L),
    delete(L1,X,L2),
    not(incompatible(L2)),
    append([X],S2,S),
    movel(L2,R,[X],S2).

movel([],_,_,[]).
movel(L,R,B,S) :-
    append(R,B,R1),
    (incompatible(R1) -> return_load(L,R,R1,S); empty_return(L,R1,S)).

empty_return(L,R,S) :-
    append([empty],S2,S),
    mover(L,R,[],S2).

return_load(L,R,R1,S) :-
    member(Y,R),
    delete(R1,Y,R2),
    not(incompatible(R2)),
    append([Y],S2,S),
    mover(L,R2,[Y],S2).

incompatible([salad,goat]). 
incompatible([goat,salad]). 
incompatible([wolf,goat]). 
incompatible([goat,wolf]). 

It generates the output

?- solve(S).
S = [goat, empty, wolf, goat, salad, empty, goat] ;
S = [goat, empty, salad, goat, wolf, empty, goat] ;
false.

Happy days.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: