Mario Parra
Mario Parra

Reputation: 1554

Generate random integer between 0 and n in intervals

I'm trying to generate a random integer between 0 and n in intervals of 4. For example, if n is 10, it will count in increments of 4 and possibly generate 0, 3, or 7 in any order: 7, 0, 3, etc. The max interval will be a variable. I've gotten as far as generating a random integer, but not from 0 or in intervals: Math.floor(Math.random() * 10) + 1;

I've seen examples of generating random integers between certain numbers, but not from 0, or in certain intervals. Thanks in advance!

Upvotes: 0

Views: 112

Answers (2)

Zac Delventhal
Zac Delventhal

Reputation: 4010

There is no reason to bother with a loop in order to do this. This solution works with just some basic arithmetic:

const randomInterval = (min, max, step) => {
  const numberOfSteps = Math.floor((max - min) / step) + 1
  const randomStep = Math.floor(Math.random() * numberOfSteps)
  return min + randomStep * step
}

console.log('0, 4, or 8 =>', randomInterval(0, 10, 4))
console.log('0, 4, 8, or 12 =>', randomInterval(0, 12, 4))
console.log('1-10 =>', randomInterval(1, 10, 1))

Upvotes: 2

user3483203
user3483203

Reputation: 51155

This lets you specify a min, max and step. It finds all the numbers that fit that category and gives you a random number from that subset.

function findRandomInInterval(min, max, step) {
  var fits = []
  for (var i = min; i < max; i += step) {
    fits.push(i)
  }
  console.log(fits[Math.floor(Math.random() * fits.length)]);
}

findRandomInInterval(0, 10, 4)

Upvotes: 1

Related Questions