Вы находитесь на странице: 1из 2

COMP 474/6741-4 Winter 2009 Lab Exercises for Week 5 Lab Instructor: Nicola Nobile

Problem 1. Prolog: U2 Crossing a Bridge "U2" has a concert that starts in 17 minutes and they must all cross a bridge to get there. All four men begin on the same side of the bridge. You must help them across to the other side. It is night. There is one flashlight. A maximum of two people cross at one time. Any party who crosses, either 1 or 2 people, must have the flashlight with them. The flashlight must be walked back and forth, it cannot be thrown, etc. Each band member walks at a different speed. A pair must walk together at the rate of the slower man's pace. Bono - 1 minute to cross Edge - 2 minutes to cross Adam - 5 minutes to cross Larry - 10 minutes to cross For example - If Bono and Larry walk across first, 10 minutes have elapsed when they get to the other side of the bridge. If Larry then returns with the flashlight, a total of 20 minutes has passed and the mission has failed. Write a Prolog program (facts and rules) to find the solution. There are several ways to code this problem. Do not worry if your solution is not the most efficient. The following facts and rules can be helpful: duration(bono, 1). duration(edge, 2). duration(adam, 5). duration(larry, 10). max(X, Y, X) :- X>Y. max(X, Y, Y) :- X=<Y. opposite(left, right). opposite(right, left). You can define rules to handle the movements of each person or persons. The direction of movement depends on which side the flashlight is on. You also will need to keep track of the current elapsed time. If the current time exceeds the elapsed time, you should stop further processing and go back to a previous state and continue from there. There are two solutions to this problem which take exactly 17 minutes.

Nicola Nobile

February 2009

Page 1 of 2

Use the following facts and rules to get started. % Member speed values duration(bono, 1). duration(edge, 2). duration(adam, 5). duration(larry, 10). % Return the maximum value max(X, Y, X) :- X>Y. max(X, Y, Y) :- X=<Y. % Return the opposite side opposite(left, right). opposite(right, left).

% Start by typing the query: go. go:solve(left, left, left, left, left, 0, [(left, left, left, left, left)]), fail. go:write('\n\nFinished\n'). % Determine if we reached the goal (flashlight and everyone on the right, and Time <= 17 solve(right, right, right, right, right, T, _):- T=<17, nl, nl. % Move Bono to the opposite side - ALONE solve(X, Edge, Adam, Larry, X, Time, BeenThere):- % Bono Alone duration(bono, TB), NewTime is Time + TB, NewTime =< 17, opposite(X, Y), \+ member((Y, Edge, Adam, Larry, Y), BeenThere), append(BeenThere, [(Y, Edge, Adam, Larry, Y)], NewBT), solve(Y, Edge, Adam, Larry, Y, NewTime, NewBT), write('Bono crosses alone from '), write(X), write(' to '), write(Y), write(': Time: '), write(NewTime), nl.

Nicola Nobile

February 2009

Page 2 of 2