12/7/2021 8:16:14 PM

Get a random number in Javascript with a lower and upper bound inclusive.

function get_random_number__start_end_inclusive(start_inclusive, end_inclusive)
{
    console.log("get_random_number__start_end_inclusive: " + start_inclusive + " | " + end_inclusive);

    //javsacripts built in function
    //returns a rnd value between 0 and 1 (not including 1)
    var rnd_initial_value = Math.random();
    console.log("rnd_initial_value", rnd_initial_value);
    
    
    //what is the range between the highest and the lowest number desired
    //ex: 1-5, range = 5, (5 - 1) + 1 
    var range = (end_inclusive - start_inclusive) + 1;
    console.log("range", range);


    //get zero based ranged using the initial rnd value
    //since the rnd_initial_value will always be under 1, rnd_initial_value * range will always be less than range
    var zero_based_rnd_number = Math.floor(rnd_initial_value * range);
    console.log("zero_based_rnd_number", zero_based_rnd_number);


    //move zero_base_rnd_number based on start_inclusive
    var final_result = zero_based_rnd_number + start_inclusive;
    console.log("final_result", final_result);


    return final_result;
}