我有一组javascript要求1到10,000之间的数字,然后继续尝试猜测该数字。我想确保计算机不会多次猜出这个数字。即猜测的数量不应超过10,000。
我已尝试使用数组和一些函数执行此操作,但显然缺少某些功能。
var upper = 10000;
var userPick = parseInt(prompt('Pick a number between 1 and 10,000'));
var computerGuess = ;
var attempts = 0;
var guessed = [];
function getRandomNumber(upper) {
return Math.floor(Math.random()*upper) + 1;
};
function testRandomNumber(){
while(guessed.indexOf(getRandomNumber!==-1))
guessed.push(getRandomNumber);
computerGuess=getRandomNumber;
} else {
getRandomNumber(upper)
}
while(computerGuess !== userPick){
computerGuess = getRandomNumber(upper);
attempts+=1;
}
document.write('<p>Your number was ' + userPick + '. The computer guessed this number after ' + attempts + ' attempts.</p>')
答案 0 :(得分:0)
在伪代码中:
let guess = an array of numbers from 1 to 10,000
shuffle guess (hint: use Fisher-Yates shuffle)
let index = 0
let notGuessed = false;
while (notGuessed && index < guess.length)
{
let thisGuess = guess[index];
notGuessed = IsThisGuessCorrect(thisGuess)
index++
}
答案 1 :(得分:0)
上面的答案很好,但我认为你甚至不需要x数量的数组。如果你有一个1 / x的概率选择正确的数字,那么改组变得无关紧要。
只需存储猜测,并声明您的下限和上限:
var guess = getUserGuess()
var min = 1
var max = 10000
然后按你的意愿向上或向下计数:
while (true && min <= max) {
min === guess ? alert('number is ' + min); return false; : min++;
}
伪代码可能会很糟糕,但我认为这样你可以获得一些性能,而无需声明一个大型数组,然后将其改组。
答案 2 :(得分:0)