Introduction To Prolog
The Box Problem
I found this one on the web a while ago and can't remember the source. If you come across it, I'll include a reference here.
Ann, Bill, Charlie, Don, Eric own one box each but we don't know which box. Try to find each box's' owner if you know that:
- Ann and Bill have boxes with the same colour.
- Don and Eric have boxes with the same colour.
- Charlie and Don have boxes with the same size.
- Eric's box is smaller than Bill's.
The following program is a nice demonstration of how Prolog uses facts and rules to solve the problems put before it. Try to solve this problem using pen and paper. Then copy the code and run that.
% First define numbers for each box.
getbox(1). getbox(2). getbox(3). getbox(4). getbox(5).
% Box number, color, size.
getbox(A), getbox(B), getbox(C), getbox(D), getbox(E),
box(A,ColorA,_), box(B,ColorA,_), % Ann and Bill have same color
box(D,ColorD,_), box(E,ColorD,_), % Don and Eric have same color
box(C,_,SizeC), box(D,_,SizeC), % Charlie and Don have same size
SizeE < SizeB. % Eric's smaller than Bill's