MojtabaSh
MojtabaSh

Reputation: 637

how can generate a random number that isn't equal to some values in jquery

is there any easy way to generate a random value that is not equal to some values

for example i want generate a value between 1 to 10

Math.floor(Math.random() * 10) + 1;

and i want it is not be equal to 3,4,7

how can do that? thank you

Upvotes: 2

Views: 239

Answers (1)

guest271314
guest271314

Reputation: 1

Try defining array of numbers which should not be returned , using Array.prototype.indexOf() to filter only numbers between 1 and 10 that are not within array containing 3 , 4, 7

var n = [3, 4, 7];

function rand(not) {
  var r = Math.floor(Math.random() * 10) + 1;
  return not.indexOf(r) === -1 ? r : rand(not)
}

console.log(rand(n))

alternatively, inverse process by defining array containing only numbers that are not 3, 4, or 7

var n = [1, 2, 5, 6, 8, 9, 10];

function rand(arr) {
  var r = Math.floor(Math.random() * arr.length);
  return arr[r]
}

console.log(rand(n))

Upvotes: 3

Related Questions