所以我有一个变量的值范围,没有办法确定确切的数字,只有一个接近它的数字(大约 50 高于或低于未知数)。所以假设正确的数字是 910(再一次,这个数字会大于或小于已经确定的数字)并且我计算 900。我将如何编写一个尝试 900、899、901、898、902 的函数, 897...等等,直到它等于未知变量?
问问题
1145 次
2 回答
1
var guess = x;
var answer = 910;
var high = guess;
var low = guess;
while (high !== answer && low !== answer) {
high++;
low--;
}
if (high === answer) {
print high;
} else if (low === answer) {
print low;
} else {
print "how did you get here?";
}
于 2013-07-04T05:26:30.750 回答
0
由于对“未知”号码的测试实际上是一个服务器调用,因此您不能使用简单的循环来执行此操作。相反,您需要异步处理所有内容。
这是一个例子:
// Starting with guess, test that value and nearby integers up through
// guess+maxDelta and down through guess-maxDelta.
// Each number is tested by calling testMagicNumber(). This function
// can make an Ajax call or other asynchronous action, and then it
// should call the callback passed to it with true or false.
// When a match is found, call the callback function with that value.
// If no match is found call the callback function with false.
function findMagicNumber( guess, maxDelta, callback ) {
var delta = 0, sign = +1;
nextNumber();
function nextNumber() {
var value = guess + sign*delta;
//console.log( 'Testing', value );
testMagicNumber( value, function( match ) {
if( match ) {
callback( value );
}
else {
if( sign > 0)
++delta;
sign = -sign;
if( delta <= maxDelta )
nextNumber();
else
callback( false );
}
});
}
}
// Test version of a magic number matcher, using a hard coded value
function testMagicNumber( value, callback ) {
callback( value == magic );
}
// Untested example of a function to test a magic number
// with a server request. isMagic(result) is whatever test
// you need to make on the result to get a boolean value
// for the callback.
function testMagicNumberAjax( value, callback ) {
$.ajax({
url: 'test',
data: { value: value },
error: function() {
callback( false );
},
success: function( result ) {
callback( isMagic(result) );
}
});
}
for( var magic = 45; magic <= 55; ++magic ) {
console.log( 'Magic number is', magic );
findMagicNumber( 50, 3, function( result ) {
console.log( 'Matched', result );
});
}
这需要 50 的猜测和 3 的最大上下增量,并测试从 45 到 55 的幻数。
记录的结果是:
Magic number is 45
Matched false
Magic number is 46
Matched false
Magic number is 47
Matched 47
Magic number is 48
Matched 48
Magic number is 49
Matched 49
Magic number is 50
Matched 50
Magic number is 51
Matched 51
Magic number is 52
Matched 52
Magic number is 53
Matched 53
Magic number is 54
Matched false
Magic number is 55
Matched false
该testMagicNumber()
函数是您进行 Ajax 调用以访问服务器的地方。当你从调用中得到响应时,testMagicNumber()
应该调用它的callback
函数参数,用true
orfalse
来指示数字是否匹配。上面有一个示例(未经测试)Ajax 版本testMagicNumberAjax()
。
您可以将上面的代码粘贴到 Chrome 控制台中进行快速测试;更改 的值magic
以尝试不同的数字。
于 2013-07-04T06:32:50.080 回答