﻿ Nicklas Gavelin - Prolog – The fox, The Goose and the Bag of Grain – D7012E Lab 32

# Prolog – The fox, The Goose and the Bag of Grain – D7012E Lab 32

Published on Sunday, April 8, 2012

Okay, so our assignment for the lab 3 was to make a prolog program to calculate all possible combinations of moves a boat with a man could make to move a Goose, a Fox and a bag of grain from one side of a river to the other without the fox eating the goose, or the goose eating the grain. The restriction was the the goose may not be left alone with the grain or that the fox may not be left alone with the goose.

I ended up with the following solution to this problem:

``````invalid(state(_,A,A,B)) :-
A \== B.
invalid(state(A,A,_,B)) :-
A \== B.

newmove(west, Move) :-
Move = east.
newmove(east, Move) :-
Move = west.

move(state(Fox, Goose, Bag, X), State, TheMove):-
State = state(Fox, Goose, Bag, Y),
newmove(X, Y),
TheMove = [nothing, Y].

move(state(X, Goose, Bag, X), State, TheMove):-
State = state(Y, Goose, Bag, Y),
newmove(X, Y),
TheMove = [fox, Y].

move(state(Fox, X, Bag, X), State, TheMove):-
State = state(Fox, Y, Bag, Y),
newmove(X, Y),
TheMove = [goose, Y].

move(state(Fox, Goose, X, X), State, TheMove):-
State = state(Fox, Goose, Y, Y),
newmove(X, Y),
TheMove = [bag, Y].

solvefgb(state(Dest, Dest, Dest, _), Dest, _, []).
solvefgb(State, Dest, N, Trace) :-
N > 0,
move(State, NewState, [Animal, Direction]),
\+(invalid(NewState)),
solvefgb(NewState, Dest, N-1, TraceCo),
Trace = [move(Animal, Direction) | TraceCo].

temp(state(west,west,west,west)).
start(T) :- temp(X), solvefgb(X, east, 8, T).
``````

Which simply is that we got a state, and the move method got 4 different moves, move goose, fox, grain or nothing over the river. N is the number of moves we max want to make and the solvefgb solves this problem if and only if N ends up bigger than 0. Else it returns false.