数字比较

< DOCTYPE html PUBLIC -WCDTD XHTML StrictEN httpwwwworgTRxhtmlDTDxhtml-strictdtd>

有12个未知数,其中有11是相等的,但有一个是不同的,而且这个不同的未知数不知道比其它11是大还是小,请问有没有办法只通过三次比次得出其中一个不同的数?
如果在你没看过任何资料的情况下答出来的话,说明你是IQ相当高了!
以下是我的答案,用程序写出来了

<html>
<head>
<title></title>
</head>

<script>
function calculate(){
var diffent_index=document.getElementByIdx("diffent_index").value;
try{
   diffent_index=parseInt(diffent_index);
}catch(e){
   alert("请输入数字");
   return;
}
if(diffent_index<1||diffent_index>12){
   alert("请输入合法的数字!1-12");
   return;
}
var x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12;
for(var i=1;i<13;i++){
   eval_r("x"+i+"=3;");
}
eval_r("x"+diffent_index+"=2;");

var compare1;
var compare2;
var compare3;
compare1=compare(x1+x2+x3+x4,x5+x6+x7+x8);
if(compare1==0){
   compare2=compare(x1+x2,x9+x10);
   if(compare2==0){
    compare3=compare(x1,x11);
    if(compare3==0){
     alert("x12");
    }else{
     alert("x11");
    }
   }else{
    compare3=compare(x1,x10);
    if(compare3==0){
     alert("x9");
    }else{
     alert("x10");
    }
   }
}else{
   compare2=compare(x1+x2+x5+x9,x3+x4+x6+x10);
   if(compare2==0){
    compare3=compare(x9,x7);
    if(compare3==0){
     alert("x8");
    }else{
     alert("x7");
    }
   }else{
    if(compare1==1 && compare2==1){//由些证明x3+x4==x5+x8,且x7证明已经是一样的数,即可根据方程移动可知x1,x2,x6存在问题,此步是理解以下的关键(可能数学移动方程)
     compare3=compare(x1+x6,x4+x3);
     if(compare3==0){
      alert("x2");
     }else{
      if(compare3==1){//从上面结果证明x1>x6,现在又证明了x1+x6>x3+x4,也就是说x6是等于x3或x4,再者x3=x4所以就x3=x4=x6,从而证明了x6重量是11个里面的
       alert("x1");
      }else{
       alert("x6")
      }
     }
    }else{
     if(compare1==1 && compare2==2){//可证明x1+x2==x6+x7即x8没问题,必定x3,x4,x5有问题,道理同上
      compare3=compare(x3+x5,x1+x2);
      if(compare3==0){
       alert("x4");
      }else{
       if(compare3==2){
        alert("x5")
       }else{
        alert("x3");
       }
      }
     }else{
      if(compare1==2&&compare2==2){
       compare3=compare(x1+x6,x4+x3);
       if(compare3==0){
        alert("x2");
       }else{
        if(compare3==2){//从上面结果证明x1>x6,现在又证明了x1+x6>x3+x4,也就是说x6是等于x3或x4,再者x3=x4所以就x3=x4=x6,从而证明了x6重量是11个里面的
         alert("x1");
        }else{
         alert("x6")
        }
       }
      }else{
       if(compare1==2&&compare2==1){
        compare3=compare(x3+x5,x1+x2);
        if(compare3==0){
         alert("x4");
        }else{
         if(compare3==1){
          alert("x5");
         }else{
          alert("x3");
         }
        }
       }
      }
     }
    }
   }
}
count=0;
}
var count=0
function compare(v1,v2){
count++;
alert("开始比较次数:"+count+"次");
if(v1==v2){
   return 0;
}else{
   if(v1>v2){
    return 1;
   }else{
    return 2;
   }
}
}
</script>
<body>
<label for="diffent_index">请设置12个数中哪个是不同的(1,12)</label>
<input type="text" id="diffent_index"/>
<input type="button" value="设定" onclick="calculate()"/>
</body>
</html>

原文地址:https://www.cnblogs.com/netcorner/p/2912151.html