Search code examples
listprologforallriver-crossing-puzzle

Choosing all possible options from List in Prolog


So I have to write different procedures that will help me solve the farmer-wolf-goat-cabbage-fertilizer puzzle. For those of you that don't know it, it involves a farmer having to cross from the North bank of a river to the South bank with all the other objects. A bank is rendered safe in 3 situations: the farmer is present OR, the wolf is not left with the goat OR, the goat is not left behind with the cabbage. For the purpose of the exercise, the variables will be [f,b,g,w,c].

The procedure (choose(Bank, Items)) I am stuck at involves finding a list of 1 or 2 elements (always including the farmer - f), that could be part of a transport from a Bank without leaving it unsafe.

If one does choose([g,f,b], Items), the possible returned values for Items can be [f], [f,g], [f,b]. However, if we do choose([g,f,c], Items), the only possible values returned are [f,c] or [f,g], since the goat and cabbage cannot be left behind together.

Thus, could anyone please give me a hint how to get all possible options for Items but in lists no longer than 2 items?


Solution

  • I can't test right now but I guess that you could write something like :

    choose(Bank, [f, Other]) :-
        select(f, Bank, Rest),
        select(Other, Rest, LeftBehind),
        safe(LeftBehind).
    choose(Bank, [f]) :-
        select(f, Bank, LeftBehind),
        safe(LeftBehind).