Home

Prolog example exercise - bookies

E-mail Print
Share/Save/Bookmark
Bookies wants to take some bets and of course they want to make profit with it. All they have are latest results from friendly matches. Predicate win(Team1, Team2, Result) means that the first team won the match with the Result.

Knowledge database

win(portugal, saudi_arabia, 3-0).    
win(mexico, paraguay, 2-1).
win(mexico, congo, 2-1).   
win(argentina, portugal, 3-2).
win(mexico, gana, 1-0).  
win(portugal, croatia, 2-0).
win(netherlands, ivory_coast, 3-1).   
win(argentina, hungary, 2-1).
win(netherlands, ecuador, 1-0).  
win(portugal, egypt, 2-0).
win(croatia, argentina, 3-2).   
win(ivory_coast, slovenia, 3-0).
win(south_corea, mexico, 1-0).   
win(netherlands, mexico, 2-1).

Write predicate gd(Team, GD) that returns the difference between all points that Team got and points that Team gave.

gd(Team, GD):-
%win
findall(X,win(Team,_,X),D),
sum(D,DWin),
%loss
findall(Y,win(Y,_,Team),D1),
sum(D1,DLoss),
GD is DWin - DLoss.

sum([],0).
sum([X|List],Sum):-
sum(List,Sum1),
Sum is X + Sum1.

What answers Prolog to following queries:

?- win(portugal, X, 2-0).

X = croatia ?;
X = egypt ?;
no

?- win(netherlands, X, _).

X =  ivory_coast ?;
X = ecuador ?;
X = ecuador ?;
no

?- win(X, mexico, _), !, win(mexico, Y, _).

X = south_corea,
Y = paraguay ? ;

X = south_corea,
Y = congo ? ;

X = south_corea,
Y = gana ? ;
no

?- win(X, Y, _-2).

X = argentina,
Y = portugal ? ;

X = croatia,
Y = argentina ? ;
no

How would you ask following questions (questions -  don't write predicates):

Which teams have been beaten by argentina?

?- win(argentina, X,_).

Did team1 won team2, team2 won team3 and team3 won team1?

?- win(X,Y,_),win(Y,Z,_),win(Z,X,_).

How many different teams did argentina played with?

?- findall(X,(win(X,argentina,_);win(argentina,X,_)),L),length(L,N).

List teams that won by at least two point difference.

findall(X,(win(X,_,N), N>=2),_List), setof(X,member(X,_List),List1).

Teams will be arranged in groups. Predicate group(Team, Group) caries information in which group team is. Team is safe (it will surely go to next round) if it hasn't been beaten by a team from the same group. Following program was written by unskilled programmer and it has errors. Correct it.

safe(Team):-
group(Team, G), group(Opponent, G), \+win(Opponent, Team, _).

Proper program :)

safe(Team):-
(group(Team, Group),
group(Opponent,Group),
win(Opponent, Team,_)) -> fail;
true.

Hits: 1939
Comments (0)Add Comment

Write comment

busy
Last Updated ( Wednesday, 27 August 2008 13:31 )  

Sponsored Links

My friends

Bookingpoint
partner websites

Donate

Do you find content useful? Please donate so I can cover my hosting expenses! Thanks!