Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Random Integer Between two Numbers

Tags:

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.

like image 549
Jack Davis Avatar asked Apr 13 '12 01:04

Jack Davis


2 Answers

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

like image 87
Ian Avatar answered Oct 24 '22 05:10

Ian


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.

like image 36
qw3n Avatar answered Oct 24 '22 05:10

qw3n