有三顶红帽子和两顶蓝帽子逻辑推理
有三顶红帽子和两顶蓝帽子。
将五顶中的三顶帽子分别戴在A、B、C三人头上。这三人每人都只能看见其他两人头上的帽子,但看不见自己头上的帽子,并且也不知道剩余的两顶帽子的颜色。
问A:”你戴的是什么颜色的帽子?”
A说:”不知道。”
问B:”你戴的是什么颜色的帽子?”
B想了想之后,也说:”不知道。”
最后问C。C回答说:”我知道我戴的帽子是什么颜色了。”
请问C戴的帽子什么颜色?
推理过程
3 红 2 蓝
三个人那么所有的组合为
红 红 红
红 蓝 蓝
红 蓝 红
红 红 蓝蓝 蓝 红
蓝 红 蓝
蓝 红 红
A B C
**【全局前提条件:A B C 至少一个 红 】**
如果A不知道,那么BC肯定不为蓝,所以排除 (红 蓝 蓝)
A
红 红 红
红 蓝 红
红 红 蓝
蓝 红 蓝
蓝 蓝 红
蓝 红 红
A B C
如果B也不知道,那么可以排除 (蓝 红 蓝);因为只有一个红,B看到两个蓝 那么肯定知道自己是红,所以排除
B
红 红 红
红 蓝 红
红 红 蓝
蓝 蓝 红
蓝 红 红
A B C
从剩下的数据中只有为 (蓝 蓝 红) 这一组时 C才知道自己是什么颜色
C
蓝 蓝 红
A B C
所以推断得出 C为红 AB 为蓝
简单的代码实现
private void calc() {
List<HashMap<String, String>> list = new ArrayList<>();
//red red red
HashMap<String, String> map1 = new HashMap<>();
map1.put("A", "red");
map1.put("B", "red");
map1.put("C", "red");
// red blue blue
HashMap<String, String> map2 = new HashMap<>();
map2.put("A", "red");
map2.put("B", "blue");
map2.put("C", "blue");
//red blue red
HashMap<String, String> map3 = new HashMap<>();
map3.put("A", "red");
map3.put("B", "blue");
map3.put("C", "red");
//red red blue
HashMap<String, String> map4 = new HashMap<>();
map4.put("A", "red");
map4.put("B", "red");
map4.put("C", "blue");
//blue blue red
HashMap<String, String> map5 = new HashMap<>();
map5.put("A", "blue");
map5.put("B", "blue");
map5.put("C", "red");
//blue red blue
HashMap<String, String> map6 = new HashMap<>();
map6.put("A", "blue");
map6.put("B", "red");
map6.put("C", "blue");
//blue red red
HashMap<String, String> map7 = new HashMap<>();
map7.put("A", "blue");
map7.put("B", "red");
map7.put("C", "red");
list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
list.add(map6);
list.add(map7);
//重要的前提条件: 三个人中至少有一个人戴红色帽子
for (int i = 0; i < list.size(); i++) {
System.out.println("1=========>" + list.get(i).get("A") + " " + list.get(i).get("B") + " " + list.get(i).get("C"));
//A不知道自己戴什么颜色 ,那么排除BC为蓝色
if (list.get(i).get("B").equals("blue") && list.get(i).get("C").equals("blue")) {
continue;
}
System.out.println("2======>" + list.get(i).get("A") + " " + list.get(i).get("B") + " " + list.get(i).get("C"));
//B不知道自己戴什么颜色 ,那么排除AC为蓝色
if (list.get(i).get("A").equals("blue") && list.get(i).get("C").equals("blue")) {
continue;
}
//排除上面的条件后,剩余可选的帽子颜色组合
System.out.println("3===>" + list.get(i).get("A") + " " + list.get(i).get("B") + " " + list.get(i).get("C"));
//根据3===>打印的日志,结合,C知道自己戴什么颜色 ,那么AC是蓝色,C是红色
if (list.get(i).get("A").equals("blue") && list.get(i).get("B").equals("blue")) {
//finally result is:
System.out.println("4===>(A B C)<->(" + list.get(i).get("A") + " " + list.get(i).get("B") + " " + list.get(i).get("C") + " )");
}
}
}
日志打印结果
![]()
![]()
![]()
总结:从上到下的分析,排除法,最后再套用全局条件和AB的回答。
题里面有漏洞。