Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected a random number from a set [closed]

I want to select a random number out of a set. For example from the set {8, 6, 1, 7}.

like image 786
BZC Avatar asked Oct 02 '13 08:10

BZC


People also ask

How do you select a random number in Matlab?

Use the rand , randn , and randi functions to create sequences of pseudorandom numbers, and the randperm function to create a vector of randomly permuted integers. Use the rng function to control the repeatability of your results.

How do I fix a random number in Excel?

To prevent an Excel random function from recalculating, use the Paste Special > Values feature. Select all the cells with the random formula, press Ctrl + C to copy them, then right click the selected range and click Paste Special > Values.

What is the range of rand ()?

rand() returns a pseudo-random number in the range of [0, RAND_MAX). RAND_MAX: is a constant whose default value may vary between implementations but it is granted to be at least 32767.


2 Answers

You can use following function to get a random number out of a set:

function getRndmFromSet(set)
{
    var rndm = Math.floor(Math.random() * set.length);
    return set[rndm];
}

in your case the call would be getRndmFromSet([8,6,1,7])

Try the jsFiddle

like image 144
Daniel Avatar answered Oct 12 '22 09:10

Daniel


var range = [8, 6, 1, 7],
    rNumber = Math.floor(Math.random()*range.length)%range.length,
    number = range[rNumber];
like image 41
Andreas Louv Avatar answered Oct 12 '22 09:10

Andreas Louv