题目:
一架飞机载着5位运动员从奥林匹克运动会归来,这5位运动员在某个项目中排名第一到第五。他们说了下面这些话:
A:”我不是最后一名。”
B:”C是第三名。”
C:”A的排名在E后面。”
D:”E是第二名。”
E:”D不是第一名。”
处于谦虚或其他什么原因,金牌和银牌的得主都说了谎。那三个成绩相对较差的运动员倒说了真话。 他们的排名到底怎样?
解决:
Java程序的解决思路
//用了lambda表达式,需要jdk8+
import static java.lang.System.out;
public class Temp{
interface Test{
abstract boolean check(int ans[]);
}
static void checkFun(int i, boolean t[], int ans[], Test[] condition){
int j;
if(i==ans.length){
for(j=0;j<condition.length;j++){
if(condition[j].check(ans) == false){
break;
}
}
if(j==condition.length){
out.println("\n(Correct )ans:");
for(int k=1;k<ans.length;k++)
out.print(""+k+":"+ans[k]+"; ");
}else{
if(true) return;
out.println("\n(Wrong )ans:");
for(int k=1;k<ans.length;k++)
out.print(""+k+":"+ans[k]+"; ");
}
}else{
for(j=1;j<t.length;j++){
if(t[j]==false){
ans[i]=j;
t[j]=true;
checkFun(i+1, t, ans, condition);
t[j]=false;
}
}
}
}
public static void main(String ...args){
Test[] tCondition = new Test[5];
tCondition[0] = (ans)->{ //A不是最后一名
boolean result=false;
if(ans[1]!=5) result=true;
if(ans[1]==1 || ans[1]==2){
if(result==false) return true;
else return false;
}
return result;
};
tCondition[1] = (ans)->{ //C是第三名
boolean result=false;
if(ans[3]==3) result=true;
if(ans[2]==1 || ans[2]==2){
if(result==false) return true;
else return false;
}
return result;
};
tCondition[2] = (ans)->{ //A的排名在E后面
boolean result=false;
if(ans[1]>ans[5]) result=true;
if(ans[3]==1 || ans[3]==2){
if(result==false) return true;
else return false;
}
return result;
};
tCondition[3] = (ans)->{ //E是第二名
boolean result=false;
if(ans[5]==2) result=true;
if(ans[4]==1 || ans[4]==2){
if(result==false) return true;
else return false;
}
return result;
};
tCondition[4] = (ans)->{ //D不是第一名
boolean result=false;
if(ans[4]!=1) result=true;
if(ans[5]==1 || ans[5]==2){
if(result==false) return true;
else return false;
}
return result;
};
boolean exist[] = new boolean[6];
int[] Tans = new int[6];
for(int i=0;i<exist.length;i++) exist[i]=false;
checkFun(1, exist, Tans, tCondition);
}
}