Random whole number between two integers algorithm doesn't work as expected?

I’m trying to dissect the random number (between two integers) algorithm provided by MDN and FreeCodeCamp. I do that by simply plugging in numbers and walking through the algorithm step by step on a piece of scratch paper.

Expected result: The random number between a range can go up to, and in fact include the max number.

I’m a bit confused about how to test it, mainly because I feel like I could be doing something wrong given the results.

Actual results: No matter what min/max I choose - my test results appear to demonstrate that the algorithm actually cannot ever result in a random number that goes “near” the max number. The result I always get will never go higher than (max-min). I’m not sure if this is the only issue with this algorithm, but it is the most obvious.

Your code so far


// Example
function ourRandomRange(ourMin, ourMax) {

return Math.floor(Math.random() * (ourMax - ourMin + 1)) + ourMin;
}

ourRandomRange(1, 9);

// Only change code below this line

function randomRange(myMin, myMax) {

return Math.floor(Math.random() * (max - min + 1)) + min;

}

var myRandom = randomRange(5, 15);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.

Challenge: Generate Random Whole Numbers within a Range

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-within-a-range

Your randomRange function will not work because max and min are not defined.

The only way to really see the function randomly generate the maximum value is to run it a large enough number of times.

Here you can see that if I run the example function enough times I will occasionally get the top bound.

1 Like