22

I'm trying to create a random number generator that generates random numbers between two numbers. For instance, let's say I want to generate a random number between 4 and 10, I would want it to be able to choose from any number from 4 - 10. Here is what I tried:

var randNumMin = 4;
var randNumMax = 10;
var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);

However, that didn't seem to work and generated weird random numbers that weren't between 4 and 10, and some began with 0. What would be the correct algorithm to do this?

Here is the code I'm implementing the algorithm in:

$(function() {
    $('#generateRandNums').click(function() {

        var numCount = document.getElementById("randNumCount").value;
        var randNumMin = document.getElementById("randNumMin").value;
        var randNumMax = document.getElementById("randNumMax").value;

        if (numCount.match(/^[\d]*$/ ) && randNumMin.match(/^[\d]*$/ ) && randNumMax.match(/^[\d]*$/ )) {       
            if (numCount == "" || randNumMin == "" || randNumMax == "")  {
                alert ("Please fill out all forms then try again.");

            } else {
                if (randNumMin>randNumMax) {
                    alert ("Please make sure your first number is smaller than the second, then try again.");
                } else {
                    if (randNumMin<0) {
                        alert ("Please make sure that you generate a positive number of random numbers, then try again.");
                    } else {

                        if (numCount>1) {
                            var randResult = ("You generated " + numCount + " random numbers between " + randNumMin + " and " + randNumMax + " and got the numbers ")
                            oneNumber = 0;
                        } else {
                            var randResult = ("You generated a random number between " + randNumMin + " and " + randNumMax + " and got the number ");
                            oneNumber = 1;
                        }
                        for (i=0;i<numCount;i++) {
                        //Get a random number between randNumMin and randNumMax
                        var randInt = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
                            if (i == numCount-1) {
                                if (oneNumber == 0) {
                                    randResult = (randResult + "and " + randInt + ".");
                                } else {
                                    randResult = (randResult + randInt + ".");
                                }
                            } else {
                                randResult = (randResult + randInt + ", ");
                            }
                        }
                        $("#randNumResults").val(randResult);
                    }
                }
            }
        } else {
            alert ("Make sure you only enter numbers and no spaces, then try again.");
        }

    });
});

I also tried replacing the randInt line with this:

var randInt = Math.floor((Math.random() * ((randNumMax + 1) - randNumMin)) + randNumMin);

It still didn't work. I'm not sure if the algorithm is wrong or I'm incorporating it wrong into the function. An answer is appreciated, thanks.

Jack Davis
  • 605
  • 4
  • 11
  • 17
  • 1
    Seems fine: http://jsfiddle.net/j08691/LYQKV/ – j08691 Apr 13 '12 at 01:46
  • I'll add the function I'm implementing it in. – Jack Davis Apr 13 '12 at 01:56
  • 1
    Possible duplicate of **[Random between two numbers in Javascript](http://stackoverflow.com/questions/4959975/random-between-two-numbers-in-javascript)** – hippietrail Aug 05 '12 at 20:03
  • 1
    Does this answer your question? [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – Heretic Monkey Mar 26 '20 at 19:30

5 Answers5

57

Generating random whole numbers in JavaScript in a specific range?

/**
 * Returns a random number between min and max
 */
function getRandomArbitary (min, max) {
    return Math.random() * (max - min) + min;
}

/**
 * Returns a random integer between min and max
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

http://roshanbh.com.np/2008/09/get-random-number-range-two-numbers-javascript.html

//function to get random number upto m
function randomXToY(minVal,maxVal,floatVal)
{
    var randVal = minVal+(Math.random()*(maxVal-minVal));
    return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}

or

Generate random number between two numbers in JavaScript

Community
  • 1
  • 1
Ian
  • 50,146
  • 13
  • 101
  • 111
  • I tried the equation in the link in the function in the question, and it didn't work. – Jack Davis Apr 13 '12 at 02:14
  • Not sure if you saw my updated answer or not, but there are multiple sources now. The first link/code is supposedly from the Mozilla Developer Center. – Ian Apr 13 '12 at 03:56
  • I have a feeling that the problem also is because you aren't converting the strings to ints. BUT this can be avoided by using the getRandomInt() function I provided above because of the order of operations. Since it completes "max - min" before adding "1", the result is an int (as long as max & min are valid numbers)...then the rest of the calculation is done as integers and should be accurate. – Ian Apr 13 '12 at 04:06
  • Sorry, I don't understand the code above. I'm fairly new to javascript. Could you explain the process of converting it into a integer a little more simple for me? – Jack Davis Apr 13 '12 at 04:28
  • The "+" operator works different for strings and integers. When you use "str" + "str", it concatenates them, combining them into "strstr" technically. When you use int + int, it adds them mathematically. When you use "str" + int, or int + "str", it concatenates them as a string because at least one of the arguments is a string. If you want to add a string and an int, you have to parseInt(Int). When you use the "-" operator, the behavior is to subtract numbers. It seems that by default, Jscript attempts to convert all arguments to numbers and if that fails, produces NaN, otherwise the result. – Ian Apr 17 '12 at 05:59
  • In the function above getRandomInt, the part: (max - min + 1) would always result in an int or NaN since the max - min occurs first (mathematical subtraction) and addition to 1. The final part where the min variable is added to the rest could possibly make weird results if it were a string, but everything could be avoided if you used parseInt(max) and parseInt(min) – Ian Apr 17 '12 at 06:02
2

Your problem is you never converted your string to numbers try adding this

if (  numCount.match(/^[\d]*$/ ) && 
    randNumMin.match(/^[\d]*$/ ) && 
    randNumMax.match(/^[\d]*$/ )){
  if (numCount === "" || randNumMin === "" || randNumMax === "")  {
    alert ("Please fill out all forms then try again.");
  } else {
    numCount=numCount-0;randNumMin=randNumMin-0;randNumMax=randNumMax-0;

Another note you need to change your checking if the value is an empty string to strict equality. To see what I mean try using zero for one of the values. 0 == ""//returns true because both are falsy 0 === ""//returns false.

qw3n
  • 6,236
  • 6
  • 33
  • 62
  • Would you know why my "Please make sure the first number is smaller than the second number" Not working when I make the first number anything but zero? – Jack Davis Apr 13 '12 at 04:35
  • @JackDavis I'm not sure what is wrong since it seems to be working fine for me. Here is a fiddle of what I have http://jsfiddle.net/YLxPr/. – qw3n Apr 13 '12 at 04:43
  • Nevermind, I just had to convert to integers before all the ifs. Also, why weren't they integers in the first place? – Jack Davis Apr 13 '12 at 13:21
  • @JackDavis you were getting them from input boxes which means they are strings so you have to convert them to numbers. – qw3n Apr 13 '12 at 13:36
2

Underscore.js has a nice utility for this _.random(min,max)

rhigdon
  • 1,483
  • 1
  • 15
  • 20
1

How about this?

var max = 10;
var min = 4;
var random = Math.floor((Math.random() * ((max + 1) - min)) + min);
mccambridge
  • 983
  • 7
  • 16
  • I implemented that in the function I posted in the question, and it still seemed to not work and give me numbers that were way to big. – Jack Davis Apr 13 '12 at 02:12
  • I reread your issue, and this code is basically the same as what you've got -- just with some extra parenthesis for readability. Don't think the issue lies in the random generator. – mccambridge Apr 13 '12 at 02:32
  • Right, I've learned that from the other comments. It's that I'm not converting into an integer. – Jack Davis Apr 13 '12 at 13:16
0

randojs.com makes this a simple one-liner:

rando(4, 10)

You just need to add this to the head of your html document, and you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.

<script src="https://randojs.com/1.0.0.js"></script>
Aaron Plocharczyk
  • 2,776
  • 2
  • 7
  • 15