`
maybe723
  • 浏览: 44940 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论

爱因斯坦问题的解法

阅读更多

题目是这样的:

 

有5个不同国籍的人,住在5所颜色不同的一排房子里,养不同的宠物,抽不同的烟,喝不同的饮料,有以下提示:

1 英国人住在红房子里

2 瑞典人养了一条狗

3 丹麦人喝茶

4 绿房子在白房子左边

5绿房子主人喝咖啡

6抽PALL MALL烟的人养了一只鸟

7黄房子的主人抽DUNHILL烟

8住在中间那间房子的人喝牛奶

9挪威人住第一间房子

10抽混合烟的人住在养猫人的旁边

11养马人住在抽DUNHILL烟的人的旁边

12抽BLUE MASTER烟的人喝啤酒

13德国人抽PEINCE烟

14挪威人住在蓝房子旁边

15抽混合烟的人的邻居喝矿泉水

问:谁养鱼?

 

 

 

public class House implements Cloneable{

 

    public int order;

    public String color="";

    public String people="";

    public String drink="";

    public String smoke="";

    public String pet="";

   

    public House(int order) {

       super();

       this.order = order;

    }

    public House(){

    }

    public House(String color, String people, String drink,

           String smoke, String pet) {

   

       this.color = color;

       this.people = people;

       this.drink = drink;

       this.smoke = smoke;

       this.pet = pet;

    }

   

    public String toString() {

       String str=order+".["+color+"],["+people+"],["+drink+"],["+smoke+"],["+pet+"]";

       return str;

    }

    public int getOrder() {

       return order;

    }

    public void setOrder(int order) {

       this.order = order;

    }

    public String getColor() {

       return color;

    }

    public void setColor(String color) {

       this.color = color;

    }

    public String getPeople() {

       return people;

    }

    public void setPeople(String people) {

       this.people = people;

    }

    public String getDrink() {

       return drink;

    }

    public void setDrink(String drink) {

       this.drink = drink;

    }

    public String getSmoke() {

       return smoke;

    }

    public void setSmoke(String smoke) {

       this.smoke = smoke;

    }

    public String getPet() {

       return pet;

    }

    public void setPet(String pet) {

       this.pet = pet;

    }

    @Override

    protected Object clone() throws CloneNotSupportedException {

       // TODO Auto-generated method stub

       return super.clone();

    }

}

 

 

import static java.lang.System.out;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Result {
	private final static String PEOPLE_ENGLISH = "英国人"; // "英国人", "瑞典人",
	// "丹麦人","挪威人", "德国人"
	private final static String PEOPLE_SWEEDEN = "瑞典人";
	private final static String PEOPLE_DANMARK = "丹麦人";
	private final static String PEOPLE_NORWAY = "挪威人";
	private final static String PEOPLE_GERMEN = "德国人";

	private final static String COLOR_RED = "红"; // "红", "白", "绿", "黄", "蓝"
	private final static String COLOR_WHITE = "白";
	private final static String COLOR_GREEN = "绿";
	private final static String COLOR_YELLOW = "黄";
	private final static String COLOR_BLUE = "蓝";

	private final static String DRINK_TEA = "茶"; // "茶", "咖啡", "牛奶", "啤酒",
	// "矿泉水"
	private final static String DRINK_COFFEE = "咖啡";
	private final static String DRINK_MILK = "牛奶";
	private final static String DRINK_BEER = "啤酒";
	private final static String DRINK_WATER = "矿泉水";

	private final static String SMOKE_PALL = "PALL MALL"; // "PALL MALL",
	// "DUNHILL",
	// "混合烟","BLUE MASTER", "PEINCE"
	private final static String SMOKE_DUNHILL = "DUNHILL";
	private final static String SMOKE_MIXTRUE = "混合烟";
	private final static String SMOKE_MASTER = "BLUE MASTER";
	private final static String SMOKE_PRINCE = "PEINCE";

	private final static String PET_DOG = "狗"; // "狗", "鸟", "猫", "马", "鱼"
	private final static String PET_BIRD = "鸟";
	private final static String PET_CAT = "猫";
	private final static String PET_HORSE = "马";
	private final static String PET_FISH = "鱼";

	private static List<House> houseList = new ArrayList<House>();
	private static List<House> conList = new ArrayList<House>();
	private static House house1 = new House(1);
	private static House house2 = new House(2);
	private static House house3 = new House(3);
	private static House house4 = new House(4);
	private static House house5 = new House(5);

	static {
		houseList.add(house1);
		houseList.add(house2);
		houseList.add(house3);
		houseList.add(house4);
		houseList.add(house5);
	}

	public static void clear() {
		for (int i = 0; i < houseList.size(); i++) {
			House h = houseList.get(i);
			h.color = "";
			h.drink = "";
			h.people = "";
			h.pet = "";
			h.smoke = "";
		}
	}

	private static void init() {
		house1.people = PEOPLE_NORWAY;
		house2.color = COLOR_BLUE;
		house3.drink = DRINK_MILK;
	}

	private static void compare(boolean check) throws Exception {
		
		boolean tempcheck=false;
		for (int i = 0; i < houseList.size(); i++) {

			for (int j = i; j < houseList.size(); j++) {
				House hi = houseList.get(i);
				House hj = houseList.get(j);
				
				if(check){
					tempcheck=(hi.order+1 <hj.order);
				}else{
					tempcheck=(hi.order+1==hj.order);
				}

				if ("".equals(hi.color) && "".equals(hj.color)
						&&tempcheck) { //
					hi.color = COLOR_GREEN;
					hj.color = COLOR_WHITE;
					for (int k = 0; k < houseList.size(); k++) {

						for (int m = 0; m < houseList.size(); m++) {
							House hk = houseList.get(k);
							House hm = houseList.get(m);

							if (hk.order == hm.order + 1 || hm.order == hk.order + 1) {
								if ("".equals(hk.pet) && "".equals(hm.smoke)) {
									hk.pet = PET_HORSE;
									hm.smoke = SMOKE_DUNHILL; // 养马人住在抽DUNHILL烟的人的旁边

									for (int n = 0; n < houseList.size(); n++) {

										for (int p = 0; p < houseList.size(); p++) {
											House hn = houseList.get(n);
											House hp = houseList.get(p);

											if (hn.order == hp.order + 1 || hp.order == hn.order + 1) {
												if ("".equals(hn.smoke)
														&& "".equals(hp.pet)) {
													hn.smoke = SMOKE_MIXTRUE;
													hp.pet = PET_CAT; // 抽混合烟的人住在养猫人的旁边
													for (int q = 0; q < houseList
															.size(); q++) {
														House hq = houseList
																.get(q);
														if ((((hn.order == hq.order - 1) || (hn.order == hq.order + 1)) && ""
																.equals(hq.drink))) { // 抽混合烟的人的邻居喝矿泉水
															hq.drink = DRINK_WATER;
															//printResult();
															getResult(getList(houseList),getList(houseList),0,0);
															hq.drink = "";
														}
													}

													hn.smoke = "";
													hp.pet = "";
												}
											}
										}
									}
									hk.pet = "";
									hm.smoke = "";
								}
							}
						}
					}
					clear();
					init();
				}
			}
		}
	}

	private static void getResult(List tempList, List<House> tempList1,
			int start, int num) throws Exception {
		if(num==conList.size()) {
		out.println("====================");
		for (int i = 0; i < tempList1.size(); i++) {
			House house = tempList1.get(i);
			out.println(house);
		}
		out.println("====================");
		return;
	   }
		
		for (int k = start; k < conList.size(); k++) {
			House hk = conList.get(k);
			Map<String, String> maps = getFields(hk);
			Iterator iterator = maps.entrySet().iterator();
			String str = "";

			while (iterator.hasNext()) {
				Map.Entry<String, String> entry = (Map.Entry) iterator.next();
				String key = entry.getKey();
				String value = entry.getValue();
				if (!"".equals(value)) {
					str += key + ",";
				}
			}
			boolean tcheck = true; // 判断条件是否符合
			for (int i = 0; i < tempList.size(); i++) {
				House house = tempList1.get(i);
				Map<String, String> houseMaps = getFields(house);
				// 把所有非空元素的拿出来
				String[] strs = str.split(",");
				if (strs.length > 0) {
					int c = 0;
					for (int m = 0; m < strs.length; m++) {
						String temp = (String) house.getClass().getField(
								strs[m]).get(house); // 得到当前节点元素的值
						String temp1 = (String) hk.getClass().getField(strs[m])
								.get(hk); // 得到当前条件的元素的值
						// 如果当前节点的值不为空以及两个条件不相等,说明该条件不符合,否则符合条件
						if (!"".equals(temp) && !temp.equals(temp1)) {
							tcheck = false;
							break;
						}else tcheck=true;
						
					}
					if (tcheck) {
						for (int m = 0; m < strs.length; m++) {
							String temp = (String) hk.getClass().getField(
									strs[m]).get(hk); // 条件的值
							if (c != strs.length) {
								setValueByField(house, strs[m], temp); // 更新条件的值
							}
						}
						num++;
						getResult(getList(tempList1), getList(tempList1), 
								k + 1, num);
						for (int m = 0; m < strs.length; m++) {
							
							if (c != strs.length) {
								setValueByField(house, strs[m], ""); // 还原条件的值
							}
						}
						num--;
					}
				}
			}
			if(tcheck) return;
		}
		return;
	}


   /**
    * 克隆list
    * @param list
    * @return
    * @throws Exception
    */
	private static List<House> getList(List<House> list) throws Exception {
		List<House> tempList = new ArrayList<House>();
		for (int j = 0; j < list.size(); j++) {
			House hou = (House) (list.get(j).clone());
			tempList.add(hou);
		}
		return tempList;
	}

	//设置当前类的字段为field的值为value
	private static void setValueByField(Object obj, String field, Object value) {

		try {
			String firstW = field.substring(0, 1);
			String methodName = "set" + firstW.toUpperCase()
					+ field.substring(1);
			Class c = obj.getClass();
			Method[] ms = c.getMethods();
			for (Method m : ms) {
				if (m.getName().equals(methodName)
						&& m.getParameterTypes().length == 1) {
					Object[] params = { value };
					try {
						m.invoke(obj, params);
						return;
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
			Field[] fs = c.getFields();
			for (Field f : fs) {
				if (f.getName().equals(field)) {
					try {
						f.set(obj, value);
						return;
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 判断条件
	private static void initCondition() {
		House house1 = new House(COLOR_RED, PEOPLE_ENGLISH, "", "", "");// 英国人住在红房子里
		House house2 = new House("", PEOPLE_SWEEDEN, "", "", PET_DOG); // 瑞典人养了一条狗
		House house3 = new House("", PEOPLE_DANMARK, DRINK_TEA, "", ""); // 丹麦人喝茶
		House house5 = new House(COLOR_GREEN, "", DRINK_COFFEE, "", ""); // 绿房子主人喝咖啡
		House house6 = new House("", "", "", SMOKE_PALL, PET_BIRD); // // MALL烟的人养了一只鸟
		House house7 = new House(COLOR_YELLOW, "", "", SMOKE_DUNHILL, ""); // 黄房子的主人抽DUNHILL烟
		House house12 = new House("", "", DRINK_BEER, SMOKE_MASTER, ""); // 抽BLUE MASTER烟的人喝啤酒
		House house13 = new House("", PEOPLE_GERMEN, "", SMOKE_PRINCE, ""); // 德国人抽PEINCE烟
		House house16 = new House("", "", "", "", PET_FISH);  //鱼
		conList.add(house1);
		conList.add(house2);
		conList.add(house3);
		conList.add(house5);
		conList.add(house6);
		conList.add(house7);
		conList.add(house12);
		conList.add(house13);
		conList.add(house16);
	}

    /**
     * 根据当前类得到所有的String类型的成员
     * @param obj
     * @return
     */
	private static Map<String, String> getFields(Object obj) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			Class cls = obj.getClass();
			Field[] fields = cls.getDeclaredFields();

			Method method;
			Object o = cls.newInstance();

			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].getName();
				String first = fieldName.substring(0, 1);
				String upFisrt = first.toUpperCase();
				String geter = "get" + upFisrt + fieldName.substring(1);
				method = cls.getMethod(geter, new Class[] {});
				Object invoke = method.invoke(obj, new Object[] {});
				if (invoke instanceof String)
					map.put(fieldName, (String) method.invoke(obj,
							new Object[] {}));
			}
		} catch (Exception e) {
		}
		return map;

	}

	public static void main(String[] args) throws Exception {
		boolean check=false; //false为相邻,true为不相邻
		init();
		initCondition();
		compare(check);
	}

}

 

 

 

分享到:
评论

相关推荐

    爱因斯坦难题C语言解法.rar

    爱因斯坦难题C语言解法 1、 在一条街上,有5座房子,喷了5种颜色。 2、 每个房里住着不同国籍的人 3、 每个人喝不同的饮料,抽不同品牌的香烟,养不同的宠物 约束条件: 1、 英国人住红色房子 2、 瑞典人养狗 3...

    爱因斯坦问题(推理题)

    爱因斯坦问题是开发大脑的一个益智题,很有意思,感兴趣的朋友可以下来试着做一下,考推理的

    爱因斯坦超级问题求解

    用回溯法求解爱因斯坦超级问题,使用的是递归的方式。

    爱因斯坦阶梯问题算法优化

    阶梯问题。有一个阶梯,若每步跨2阶,最后余1阶;若每步跨3阶,最后余2阶;若每步跨5阶,最后余4阶;若每步跨6阶,最后余5阶。当每步跨7阶时,刚好达到阶梯顶部。 此问题的动画教程

    实验三:prolog求解爱因斯坦的超级问题(人工智能实验报告)

    包含prolog求解爱因斯坦的超级问题的实验报告、源代码及试验运行截图

    爱因斯坦棋

    这是一个爱因斯坦博弈棋,已经实现了人工智能,还有点缺陷,没有做界面,

    爱因斯坦难题 程序

    很早以前就看到爱因斯坦的这道推理题,据说只有2%的聪明人才能做出来,我不属于那2%,可我想知道答案... 于是就有了这个想法,编程借助计算机计算。 五个人分别来自五个国家,那么就有P55=120种可能,同样五个人...

    C++下爱因斯坦棋策略的实现

    对于爱因斯坦棋游戏的评估策略及走子的实现,内附有pdf版的评估策略思路,可供学习使用

    【爱因斯坦】思考喜欢的问题

    爱因斯坦的思考题题目:有五个具有五中不同颜色的房间;每个房间里分别住着一个不同国籍的人;每个人都在喝特定品牌的饮料,抽特定品牌的香烟,养特定的宠物;没有任意两个人在抽相同品牌的香烟,或喝相同品牌的饮料...

    爱因斯坦年5篇论文原著集.zip

    爱因斯坦年 5篇原文打包,分别是:分子大小的新测定 关于光的产生和转化的一个启发性观点 论动体的电动力学 热的分子运动论所要求的静液体中悬浮粒子的运动 一个物体的惯性依赖它的能量吗

    爱因斯坦双场方程

    等同于最近确定的弦状爱因斯坦曲率张量,闭弦无质量扇形的所有运动方程都统一成一个表达式,$ G_ {AB} = 8 \ pi G T_ {AB} $$ GAB =8πGTAB, 我们将其称为爱因斯坦双场方程。 例如,我们研究最普通的$$ {D = 4} $$...

    爱因斯坦英语简介PPT课件.pptx

    爱因斯坦英语简介PPT课件.pptx

    爱因斯坦难题c语言代码

    就是爱因斯坦难题的C语言源代码,附加注解

    通用3D重力理论中的非爱因斯坦黑洞

    Bañados-Teitelboim-Zanelli(BTZ)黑洞度量标准解决了具有负宇宙学常数的三维爱因斯坦理论以及基于该度量标准的所有通用的更高阶导数引力理论。 因此,这是一个通用的解决方案。 在这里,我们发现在所有通用的更高...

    C# Wpf 设计的游戏:爱因斯坦的超级问题 -- 谁养鱼

    自己用WPF仿FLASH小游戏做的,WPF设计的界面实在让人惊叹,有兴趣可以下载看看,包括源码和可执行程序,需要.NET3.0运行库以上支持,程序特点在于界面,代码部分没有刻意处理,包括对自定义标题栏的处理,开发工具:...

    探索的动机 爱因斯坦

    每个做研究的人必看 它能够给人们思想上的开导 提升人的境界 是爱因斯坦的经典语录

    完整版爱因斯坦的难题.rar

    完整版爱因斯坦的难题.rar

    爱因斯坦-1905-博士学位论文

    这就是爱因斯坦的当年的博士毕业论文,有兴趣的人来看看吧.

    关于大双引力背景下爱因斯坦静态宇宙的稳定性

    通过在宇宙方程中对理想流体提出的修改,我们获得了被解释为爱因斯坦静态宇宙的新解。 事实证明,爱因斯坦静态宇宙的初始比例因子的不消失大小取决于FRW度量的不消失的三维空间曲率以及引力子的质量。 通过动力学...

    完整版爱因斯坦的难题.e.rar

    完整版爱因斯坦的难题.e.rar

Global site tag (gtag.js) - Google Analytics