Answer the question
In order to leave comments, you need to log in
How to fix an error in the wolf, goat and cabbage problem in prolog?
There is a known task: A farmer has a wolf, a goat and a cabbage. All of them are located on the left bank of the river. It is necessary to transport this "trio" to the right bank, but one thing can fit in the boat - a wolf, a goat or a cabbage. You can not leave a wolf with a goat and a goat with cabbage on the same bank.
Solution taken from here: https://pro-prof.com/archives/1299
check(L):-
member(wolf, L), !, not(member(goat, L));
member(goat, L), !, not(member(cabbage, L));
!.
generate((Left, Right, left)):-
permutation_length(Left, 1, LeftPart),
subtraction(Left, LeftPart, NewLeft),
append(LeftPart, Right, NewRight),
check(NewLeft),
not(edge(_, (NewLeft, NewRight, right))),
assert(edge((Left, Right, left), (NewLeft, NewRight, right))),
fail;!.
generate((Left, Right, right)):-
permutation_length(Right, 1, RightPart),
subtraction(Right, RightPart, NewRight),
append(RightPart, Left, NewLeft),
check(NewRight),
not(edge(_, (NewLeft, NewRight, left))),
assert(edge((Left, Right, right), (NewLeft, NewRight, left))),
fail;!.
path(Finish, [[Finish | PathPart] | _], [Finish | PathPart]):-!.
path(Finish, [[X | PathPart] | ProcList], Path):-
generate(X),
findall(Y, step(X, PathPart, Y), AdjNodes),
append(ProcList, AdjNodes, NewProcList), !,
path(Finish, NewProcList, Path).
step(X,T,[Y,X|T]):-
edge(X,Y),
not(member(Y,T)).
path(Start, Finish):-
path(Finish, [[Start]], RPath), !,
reverse(RPath,Path), write(Path).
path(([wolf, goat, cabbage], [], left), ([], _, right)).
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question