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.

box problem image

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.
box(1,black,3).
box(2,black,1).
box(3,white,1).
box(4,black,2).
box(5,white,3).
owners(A,B,C,D,E):-
getbox(A), getbox(B), getbox(C), getbox(D), getbox(E),
A\=B,A\=C,A\=D,A\=E,
B\=C,B\=D,B\=E,
C\=D,C\=E,
D\=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
box(E,_,SizeE), box(B,_,SizeB),
SizeE < SizeB. % Eric's smaller than Bill's