网上看到的一个题,在某个网页上发现了关于这个题目的应用,是用js写的,分享下源代码(稍作了修改):
1 function tdisoper(f0,f1,f2,f3) 2 { 3 this[0]=f0; 4 this[1]=f1; 5 this[2]=f2; 6 this[3]=f3; 7 } 8 disoper=new tdisoper("-","+","/","*"); 9 function oper(f,m,n) 10 { 11 if (f==3) return(m*n); 12 if (f==2) return(m/n); 13 if (f==1) return(parseFloat(m)+parseFloat(n)); 14 if (f==0) return(m-n); 15 } 16 function tb(i1,i2,i4,i8) 17 { 18 this[1]=i1; 19 this[2]=i2; 20 this[4]=i4; 21 this[8]=i8; 22 } 23 function get24(n1,n2,n3,n4) 24 { 25 var result=""; 26 b=new tb(n1,n2,n3,n4); 27 k=0; 28 for (i1=1;i1<=8;i1*=2) 29 for (i2=1;i2<=8;i2*=2) 30 for (i3=1;i3<=8;i3*=2) 31 for (i4=1;i4<=8;i4*=2) 32 { 33 if ((i1|i2|i3|i4)!=0xf) continue; 34 for (f1=0;f1<=3;f1++) 35 for (f2=0;f2<=3;f2++) 36 for (f3=0;f3<=3;f3++) 37 { 38 m=oper(f3,oper(f2,oper(f1,b[i1],b[i2]) ,b[i3] ) ,b[i4]); 39 if (Math.abs(m-24)<1e-5 ) { 40 result+=(("+b[i1]+disoper[f1]+b[i2]+")"+disoper[f2]+b[i3]+")"+disoper[f3]+b[i4]+"\n"; 41 } 42 m=oper(f1, b[i1], oper(f3, oper(f2,b[i2],b[i3]) ,b[i4]) ); 43 if (Math.abs(m-24)<1e-5){ 44 result=result+b[i1]+disoper[f1]+"(("+b[i2]+disoper[f2]+b[i3]+")"+disoper[f3]+b[i4]+")\n"; 45 } 46 m=oper(f3,oper(f1,b[i1], oper(f2,b[i2],b[i3]) ),b[i4]); 47 if (Math.abs(m-24)<1e-5){ 48 result=result+"("+b[i1]+disoper[f1]+"("+b[i2]+disoper[f2]+b[i3]+"))"+disoper[f3]+b[i4]+"\n"; 49 } 50 m=oper(f1, b[i1], oper(f2, b[i2], oper(f3, b[i3], b[i4]) ) ); 51 if (Math.abs(m-24)<1e-5){ 52 result=result+b[i1]+disoper[f1]+"("+b[i2]+disoper[f2]+"("+b[i3]+disoper[f3]+b[i4]+"))\n"; 53 } 54 m=oper(f2,oper(f1,b[i1],b[i2]), oper(f3,b[i3],b[i4]) ); 55 if (Math.abs(m-24)<1e-5){ 56 result=result+"("+b[i1]+disoper[f1]+b[i2]+")"+disoper[f2]+"("+b[i3]+disoper[f3]+b[i4]+")\n"; 57 } 58 59 } 60 } 61 alert(result); 62 return(false); 63 }