A〜Eは青か赤か白の帽子をかぶっている。いずれの色の帽子も誰かがかぶっており他人の帽子の色はわかるが自分の帽子の 色はわからない。A〜C3人は帽子の色について同時にそれぞれ次のように言った。
A「白二人」、 B「白二人」、 C「BD同じ」
また5人のうちDEのどちらか一人だけが嘘を言う事がわかっている。今ある人がDに対して「EはAの帽子の色についてどう答えたか」と尋ねると、
D「赤と答えた」
と言った。この時確実に言えるのは?
ア、青は一人。 イ、青は二人。 ウ、白は二人。 エ、白は三人。 オ、赤は一人。
ちなみに、条件Dは、「Aは赤ではない」と同じことです。(^_^;
● ColorHat1.java
/* * ColorHat1.java */ class ColorHat1 { public static int countMatches(String s, char c) { int n = s.length(); int count = 0; for(int i=0; i< n; i++) if(s.charAt(i)==c) count++; return(count); } public static void main(String[] args) { final String NAME = "ABCDE"; final String COLORS = "青赤白"; char[] colors = COLORS.toCharArray(); boolean[] ch = {true,true,true,true,true}; long tm=System.nanoTime(); // Timer Start System.out.println(NAME); for(char a : colors){ if(a=='赤') continue; // 条件D for(char b : colors){ for(char c : colors){ for(char d : colors){ if(b!=d) continue; // 条件C for(char e : colors){ char[] p = {b,c,d,e}; if(countMatches(new String(p),'白')!=2) continue; // 条件A char[] q = {a,c,d,e}; if(countMatches(new String(q),'白')!=2) continue; // 条件B char[] r = {a,b,c,d,e}; String s = new String(r); int iBlu = countMatches(s,'青'); int iRed = countMatches(s,'赤'); int iWhi = countMatches(s,'白'); if(iBlu*iRed*iWhi==0) continue; // どの色も誰かが被っている条件 // チェックを潜り抜けたものだけを表示 System.out.println(s); // 選択肢のチェック if(iBlu==1) ch[0]&=true; else ch[0]&=false; if(iBlu==2) ch[1]&=true; else ch[1]&=false; if(iWhi==2) ch[2]&=true; else ch[2]&=false; if(iWhi==3) ch[3]&=true; else ch[3]&=false; if(iRed==1) ch[4]&=true; else ch[4]&=false; } } } } } System.out.print("∴"); for(int i=0; i< 5; i++) if(ch[i]) System.out.println(" "+(i+1)); tm=System.nanoTime()-tm; // Timer Stop System.out.printf("Runtime : %.3f [sec]\n",(double)tm/1e9); } }
●実行結果
ABCDE 青赤白赤白 白白青白赤 白白赤白青 ∴ 1 Runtime : 0.001 [sec]