methuselah
methuselah

Reputation: 13206

Create a range between two numbers in JavaScript

Given an upper bound in array - elementsGroupItemsCount, for example, which has 101 elements. How would I randomly select a minimum and maximum value from this range 0-100, where the minimum and maximum value are n numbers apart and need to contain n elements.

E.g. if the numbers need to be contain 6 elements, the following would be valid solutions:

I've seen how to generate random numbers in a range, but not sets of random numbers that are interrelated to each other.

Upvotes: 2

Views: 1677

Answers (3)

AFLAH ALI
AFLAH ALI

Reputation: 451

getNRandomNumbers = (elementsGroupItems,requiredSpan) => {
  var result = []
  var startingValue = elementsGroupItems[0]
  var endingValue = elementsGroupItems[elementsGroupItems.length -1]
  var initialNum = startingValue + Math.floor(Math.random()*(endingValue - requiredSpan))
  for(let i=initialNum; i< (initialNum+requiredSpan); i++){
    result.push(i)
  }
  return result
}

console.log(getNRandomNumbers([1,2,3,4],2)) //example

Upvotes: 0

jdc
jdc

Reputation: 384

Just to complete the Mark Taylor's Answer here a more reusable way

let myArray = [];

for (let i = 0; i<101; i++){
  myArray.push({objectID:i})
}

const randomMaxMin = max => min => Math.floor(Math.random()*(max-min))
const lowerBand = requiredSpan => length => randomMaxMin(length)(requiredSpan);
const upperBand = requiredSpan => lowerBand => requiredSpan + lowerBand-1;

const getLowerAndUpperBand = requiredSpan => length => {
  const lower = lowerBand(requiredSpan)(length);
  return {
    lower: lower,
    upper: upperBand(requiredSpan)(lower)
  }
}

console.log(getLowerAndUpperBand(6)(myArray.length))

You can even specialize the generic function by choosing the requiredSpan

const getLowerAndUpperBandSix = getLowerAndUpperBand(6)
console.log(getLowerAndUpperBandSix(myArray.length))

Upvotes: 2

Mark Taylor
Mark Taylor

Reputation: 1188

As per Bob's comment it looks like you just need to get a random number between 0 and the array length (less the required span) for your lower limit and then add the required span back to it for the upper limit. e.g.

let myArray = [];

for (let i = 0; i<101; i++){
  myArray.push({objectID:i})
}

let requiredSpan = 6;
let lowerBand = Math.floor(Math.random()*(myArray.length-requiredSpan));
let upperBand = lowerBand + requiredSpan-1;

console.log(lowerBand, upperBand);

Upvotes: 3

Related Questions