I'm looking to generate a random number between 1000 & 2000 for the time of day, it has to be in 100 increments. It's so I can test prebid timeouts and see different viewability figures and cpm's. Then once I get enough data, I can work out the best settings for any given time of day and hopefully get better results.

help would be much appreciated.

This is what i have so far but i'm changing them by hand depending on the time of day I see peaks and troughs in traffic at the moment:

var timeoutMap = {0 : 2000,1 : 2000,2 : 2000,3 : 1600,4 : 1600,5 : 1600,6 : 1400,7 : 1400,8 : 1400,9 : 1400,10 : 1400,11 : 1400,12 : 1600,13 : 1600,14 : 1600,15 : 1600,16 : 1600,17 : 1600,18 : 1600,19 : 1600,20 : 1600,21 : 1600,22 : 1600,23 : 2000};var t = new Date().getUTCHours();PREBID_TIMEOUT = timeoutMap[t];console.log("prebid timeout:", PREBID_TIMEOUT );
1

Best Answer


The general formula would be minValue + randomFloatBetweenZeroAndOne * (maxValue - minValue). Then to get the steps of 100 it would be randomNumGeneratedInPreviousStep / 100, rounded to nearest int, then multiplied by 100.

function generateRandom() {const randomNum = 1000 + Math.random() * 1000;return Math.round(randomNum / 100) * 100;}

EDIT:

To make it more generic and allow you to customize aspects of this:

function generateRandom(min, max, step) {const randomNum = min + Math.random() * (max - min);return Math.round(randomNum / step) * step;}

If you wanted to apply this to your object for each value in your object, I would not make it super generic unless you knew you wanted to use it elsewhere. If that were the case, I'd wrap the general function in a more specialized function that closed on your specified values for this specifc use-case and do something like this:

const MIN_RANDOM = 1000;const MAX_RANDOM = 2000;const RANDOM_STEP = 100;function generateRandom(min, max, step) {const randomNum = min + Math.random() * (max - min);return Math.round(randomNum / step) * step;}function myRandom() {return generateRandom(MIN_RANDOM, MAX_RANDOM, RANDOM_STEP);}var timeoutMap = {0 : myRandom(),1 : myRandom(),2 : myRandom(),3 : myRandom(),...};