-1

I am trying to generate four different numbers for my text based survival game I am making for school. I am just having trouble with this part I have look at other similar questions but they want the four number, the number postal code and a bunch of other fancy stuff. I need just four numbers that are different. i was doing Math.random as so

>***'int event_W =(int)( Math.random()*10 + 1);

 int event_X =(int)( Math.random()*10 + 1);

 int event_Y =(int)( Math.random()*10 + 1);

 int event_Z =(int)( Math.random()*10 + 1);***

and the numbers cant be greater then ten or less then 0

Farmer
  • 1
  • 1

2 Answers2

0

You can use Math.random to generate numbers and keep checking if the newly generated number is already in your array.

var arr = []
while(arr.length < 4){
   var randomnumber = Math.random()
   if(arr.indexOf(randomnumber) > -1) continue;
   arr[arr.length] = randomnumber;
}
console.log(arr)
alpeshpandya
  • 492
  • 3
  • 12
0

This function will return an array of random ints between a min and max.

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

function fetchRandomArray(min, max, num){
  var random = [];
  while(random.length < num){
    var randomNum = getRandomInt(min, max);
    if(random.indexOf(randomNum) < 0){
      random.push(randomNum);
    }
  }
  return random;
}

console.log(fetchRandomArray(1, 10, 4));
Jordan Soltman
  • 3,795
  • 17
  • 31