最近在微博上看到一篇有关爱因斯坦养鱼问题的文章,文章里面说世界上有98%的人解不出来这个问题。因为最近在学constriants processing的课,于是我试着用ECLiPSe编写了一个程序来解决这个问题。ECLiPSe是一个基于Prolog的Constraint Processing工具,非常强大。废话少说,附上代码:
% Constraints satisfaction problem from Albert Einstein
% Author : Feng Di @K.U.Leuven
% Please run this program by ECLiPSe
% ECLiPSe is a constraint processing tool using Prolog
:-lib(ic).
einstein_problem:-
% I use 5 list of 5 variables
Nat = [English,Swedes,Danish,Norwegian,German],
Color = [Red,White,Green,Yellow,Blue],
Pat = [Dog,Bird,Cat,Horse,Fish],
Drink = [Tea,Coffee,Milk,Beer,Water],
Cigarette = [PallMall,Dunhill,Blends,BlueMaster,Prince],
%domain of variables
Nat :: 1..5,
Color :: 1..5,
Pat :: 1..5,
Drink :: 1..5,
Cigarette :: 1..5,
%constraints
alldifferent(Nat),
alldifferent(Color),
alldifferent(Pat),
alldifferent(Drink),
alldifferent(Cigarette),
English $= Red,
Swedes $= Dog,
Danish $= Tea,
White #= Green+1,
Green $= Coffee,
PallMall $= Bird,
Yellow $= Dunhill,
Milk $= 3,
Norwegian $= 1,
abs(Blends-Cat) $= 1,
abs(Horse-Dunhill) $= 1,
BlueMaster $= Beer,
German $= Prince,
abs(Norwegian-Blue) $= 1,
abs(Blends-Water) $=1,
%search
flatten([Nat,Color,Pat,Drink,Cigarette],List),
labeling(List),
%print solution
NatNames = [English-english,Swedes-swedes,Danish-danish,Norwegian-norwegian,German-german],
memberchk(Fish-FishNat,NatNames),
write('The '),write(FishNat),write(' owns fish.'),nl.
附:
爱因斯坦养鱼问题:
世界上最难的一道题!爱因斯坦在20世纪初出的这个谜语。他说世界上有98%的人答不出来。聪明的你,试试吧!
1、在一条街上,有5座房子,喷了5种颜色。
2、每个房里住着不同国籍的人
3、每个人喝不同的饮料,抽不同品牌的香烟,养不同的宠物
问题是:谁养鱼?
提示:
1、英国人住红色房子
2、瑞典人养狗
3、丹麦人喝茶
4、绿色房子在白色房子左面
5、绿色房子主人喝咖啡
6、抽PallMall香烟的人养鸟
7、黄色房子主人抽Dunhill香烟
8、住在中间房子的人喝牛奶
9、挪威人住第一间房
10、抽Blends香烟的人住在养猫的人隔壁
11、养马的人住抽Dunhill香烟的人隔壁
12、抽BlueMaster的人喝啤酒
13、德国人抽Prince香烟
14、挪威人住蓝色房子隔壁
15、抽Blends香烟的人有一个喝水的邻居