先举个例子,我不知道这个例子有没有答案哈:

a + b * c / d + e - f - g + 12 / 8 * h / i = 10

请把a~i填入1-9这9个数字,使用等式成立。9个变量对应9个数字,必须是一对一的。这种题蛮伤脑筋的,所以,用枚举来搞定算了!

看看代码:

var a,b,c,d,e,f,g,h,i;

var res = 0;

for(a=1;a<=9;a++){

for(b=1;b<=9;b++){

if( b == a ) continue;

for(c=1;c<=9;c++){

if( c == a ) continue;

if( c == b ) continue;

for(d=1;d<=9;d++){

if( d == a ) continue;

if( d == b ) continue;

if( d == c ) continue;

for(e=1;e<=9;e++){

if( e == a ) continue;

if( e == b ) continue;

if( e == c ) continue;

if( e == d ) continue;

for(f=1;f<=9;f++){

if( f == a ) continue;

if( f == b ) continue;

if( f == c ) continue;

if( f == d ) continue;

if( f == e ) continue;

for(g=1;g<=9;g++){

if( g == a ) continue;

if( g == b ) continue;

if( g == c ) continue;

if( g == d ) continue;

if( g == e ) continue;

if( g == f ) continue;

for(h=1;h<=9;h++){

if( h == a ) continue;

if( h == b ) continue;

if( h == c ) continue;

if( h == d ) continue;

if( h == e ) continue;

if( h == f ) continue;

if( h == g ) continue;

for(i=1;i<=9;i++){

if( i == a ) continue;

if( i == b ) continue;

if( i == c ) continue;

if( i == d ) continue;

if( i == e ) continue;

if( i == f ) continue;

if( i == g ) continue;

if( i == h ) continue;

res = a + b;

res = res * c;

if(res % d != 0) continue;

res = res / d;

if(res < 0) continue;

res = res - e;

if(res < 0) continue;

res = res + f;

res = res * 10;

res = res - 43;

if(res < 0) continue;

res = res / 11;

res = res + 12;

res = res - g;

if(res < 0) continue;

res = res * h;

if(res % h != 0) continue;

res = res / i;

if( res == 20 ){

console.log([a,b,c,d,e,f,g,h,i]);

}

}

}

}

}

}

}

}

}

}

代码写得可能很糟糕,不简练,但大概意思是对的。有几点要注意的:

1、每个数字不一样。所以枚举的时候,遇到当前变量等于之前的变量时,要跳出当前循环。

关于JavaScript枚举数字1-9满足某个等式的算法,本文就介绍这么多,希望对大家有所帮助!

03-14 10:03