2016-04-20 178 views
2

任務是猜測3個數字:x,y和z只需知道它們中每兩個的總和。bruteforcing do ... while或while循環

我懷疑多個條件可能不起作用。

在這個測試案例中,答案很明顯:每個數字都是5,但由於某種原因代碼無法正常工作。這似乎察覺到的任務,因爲一旦解決任何變量的總和是10

var bruteforce = function(){ 
    var i = 0; 
    var x = 0; //tie 
    var y = 0; //jacket 
    var z = 0; //shirt 

    while (x+y !== 10 && z+y !== 10 && z+x !== 10){ 
    var x = 1 + Math.floor(Math.random() * 10); 
    var y = 1 + Math.floor(Math.random() * 10); 
    var z = 1 + Math.floor(Math.random() * 10); 
    i++; 
    } 

    console.log('Solved at ' + i + ' attempts.'); 
    console.log('x = ' + x); 
    console.log('y = ' + y); 
    console.log('z = ' + z); 

}; 

bruteforce(); 

小提琴是在這裏:https://jsfiddle.net/9cpbfsof/2/

+1

爲什麼選擇bruteforce?使用數學! 'x =(sum_xy + sum_xz-sum_yz)/ 2'。 – Oriol

+0

@Oriol Hm ...如果x + y = 205; X + Z = 130; y + z = 225,那麼建議的解決方案給出x爲110/2 = 55.「強力」建議x爲40.它只需要14.5M的嘗試,這很有趣:) – Vadimster

+1

然後你的蠻力是錯誤的。唯一的解決方案是'x = 55','y = 150','z = 75',參見[Wolframalpha](http://www.wolframalpha.com/input/?i=solve+x%2By%3D205, + X%2BZ%3D130,+ Y%2BZ%3D225)。如果「x = 40」,則意味着「y = 205-40 = 165」和「z = 130-40 = 90」,但是「165 + 90 = 255」而不是「225」。 – Oriol

回答

4
在你的病情

您應該使用的OR(||):

while (x+y !== 10 || z+y !== 10 || z+x !== 10){ 
    var x = 1 + Math.floor(Math.random() * 10); 
    var y = 1 + Math.floor(Math.random() * 10); 
    var z = 1 + Math.floor(Math.random() * 10); 
    i++; 
} 

由於您的情況是負面的,如果其中任何一個失敗,您都希望繼續前進。 使用AND時,如果其中任何一個成功,就會停止。使用OR時,一旦它們全部成功,就停下來。

此外,我不認爲你應該使用var你的循環中:

while (x+y !== 10 || z+y !== 10 || z+x !== 10){ 
    x = 1 + Math.floor(Math.random() * 10); 
    y = 1 + Math.floor(Math.random() * 10); 
    z = 1 + Math.floor(Math.random() * 10); 
    i++; 
} 

記錄:81次嘗試:)

+0

啊thanx很多,當然,愚蠢的我:) – Vadimster

0

一旦一個條件滿足循環結束,所以它的行爲如預期。使用|| (或)條件在while語句中。