Basic JavaScript - Generate Random Whole Numbers within a Range

I don’t understand why this code wouldn’t do what the topic is asking for. I wrote separate code to test it thousands of times, and it seems to do the right thing.

Thanks for your time!!

function randomRange(myMin, myMax) {
  return Math.ceil(Math.random() * (myMax - myMin) + myMin);
}

Challenge: Basic JavaScript - Generate Random Whole Numbers within a Range

Link to the challenge:

The instructions specifically ask for floor instead of ceiling. The rounding with ceiling won’t ever produce the mininum number.

Thank you, I understand my mistake, now.

As an exercise, I also tried to find how the alternative with .floor() could work, and I came up with:

function randomRange(myMin, myMax) {
  myMin--;
  return Math.ceil(Math.random() * (myMax - myMin)) + myMin;
}

This works perfectly, but still doesn’t pass the test :smiley:

I’ve written this other code to run tests on my fixed code, returning and object with a count for each number.

function randRangeTest(min, max, quant) { // quant = amount of tests to run

// Create an object with a property for each number, and a counter = 0
    let list = {};
    for (var i = min; i <= max; i++) {
        list[i] = 0;
    }

// Run 'quant' amount of tests and count results
    while (quant-- > 1) {
        list[randomRange(min, max)]++; 
    };

    return list;
}

Now, calling, for example, randRangeTest(3, 20, 1000000) performs ten million tests in the 3-20 range, and returns a count for every result (which they tend to be rather equal, from where I assume that the randomness of JS might have a system to ‘equalize’ the results (or simply ‘chance’ plays a fair role!!)

On this last edit, I’m taking advantage of the fact that quant-- returns the original value before deducting 1 from it. I find it poetic… :slight_smile: