-2

I was wondering how I can make a JavaScript loop that have to guess a correct number, 1-500.

Every loop there should be a new unique number that hasn't been guessed before. However it should guess in a random order.

Yes:

351, 201, 97 ...

No:

1, 2, 3, 4, 5, 5 ...

My code so far:

var number;

setInterval(function(){

number = Math.floor(Math.random() * 500) + 1;
console.log(number);

if (number == 350) {
console.log("Correct Number!")
}
}, 1000)
Insanic
  • 71
  • 9
  • Create an array that has every number in the range, shuffle the array, read out the values. – 4castle Apr 30 '17 at 22:01
  • Possible duplicate of [Generate unique random numbers between 1 and 100](http://stackoverflow.com/questions/2380019/generate-unique-random-numbers-between-1-and-100) – 4castle Apr 30 '17 at 22:07

2 Answers2

1

Here is my attempt at solving your problem using a fisher yates shuffle on an array with all numbers between 500.

var number = 121;

var numbArr = [];

for(var x = 1; x <= 500; x++){
  numbArr.push(x);
}

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
}

shuffle(numbArr);

for(var x = 0; x < numbArr.length; x++){
  if(number == numbArr[x]){
        console.log("Found number at entry " + x);
  }
}

The guessing with a random number comes by using the shuffle of all the possible numbers which means that it shall not be guessed again.

li x
  • 3,953
  • 2
  • 31
  • 51
-1

You will need to store the numbers you have already randomed. If you encountered a number you have already randomed, random again.

var usedNumbers = [];
var interval = setInterval(function(){

    var number = Math.floor(Math.random() * 500) + 1;

    while(usedNumbers.includes(number)){
        number = Math.floor(Math.random() * 500) + 1;
    }
    usedNumbers.push(number);
    if (number == 350){
        console.log("Correct Number!");
        clearInterval(interval);
        return;
    }
    console.log(number);
}, 500)
  • This is heavily inefficient as like the op described "Every loop there should be a new unique number" Within you solution non unique numbers can be tested. – li x Apr 30 '17 at 22:21