I want to select a random number out of a set. For example from the set {8, 6, 1, 7}.
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.
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.
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.
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
var range = [8, 6, 1, 7],
rNumber = Math.floor(Math.random()*range.length)%range.length,
number = range[rNumber];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With