Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1264 How to generate a random integer within and including two limits. For example: 3 & 7. How to randomly generate 3, 4, 5, 6 or 7?

irt.org | Knowledge Base | JavaScript | Random | Q1264 [ previous next ]

Q1264 How to generate a random integer within and including two limits. For example: 3 & 7. How to randomly generate 3, 4, 5, 6 or 7?

There are three useful methods:

METHOD#1. Hardcode the numbers into the function...

function getRandom()
{
   return (Math.round(Math.random()*(7-3)))+3;
}

myRandomNumber = function getRandom();

METHOD#2. Pass the numbers to the function...

function getRandom(min,max)
{
   return (Math.round(Math.random()*(max-min)))+min;
}

myRandomNumber = function getRandom(3,7);

METHOD#3. Pass the variables to the function...

function getRandom(min,max)
{
   return (Math.round(Math.random()*(max-min)))+min;
}

var myLoNumber = 3;
var myHiNumber = 7;

myRandomNumber = function getRandom(myLoNumber,myHiNumber);

Submitted by Joe Barta


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.