How to Get Random Value Out of an Array

Getting a random value from a JavaScript array

It's a simple one-liner:

const randomElement = array[Math.floor(Math.random() * array.length)];

For example:

const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);

Get a random item from a JavaScript array

var item = items[Math.floor(Math.random()*items.length)];

How to get random value out of an array?

You can also do just:

$k = array_rand($array);
$v = $array[$k];

This is the way to do it when you have an associative array.

How to pick a random value out of an array with a specific proportion?

You can have an array of size 20 that contains the relative portion of your labels, and represent the exact percentage of each label.

Then, all you need to do is random of 1-20, the result will use as index to choose from the array.

 var diffSev = [
'CRITICAL',
'ERROR', 'ERROR',
'INFO', 'INFO', 'INFO', 'INFO', 'INFO', 'INFO',
'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG', 'DEBUG'
]

return diffSev[Math.floor(Math.random() * 20)];

How to get a number of random elements from an array?

Try this non-destructive (and fast) function:

function getRandom(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len)
throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}

How to randomly pick an element from an array

public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}

How do I select a random item out of an array?

You do this by:

  1. Generating a random index into the array (in your case between 0 and 2); let that index be i.
  2. Emitting rpsoptions[i].

As @ThomasSablik notes, the first step is covered by this question:

How to generate a random number in C++?

Combining the two steps, here is what you could get for your program:

#include <random>
#include <iostream>

int main()
{
std::random_device dev;
std::mt19937 randomness_generator(dev());
std::uniform_int_distribution<std::size_t> index_distribution(0,2);

std::string rpsoptions[3] = {"rock", "paper", "scissors"};

auto i = index_distribution(randomness_generator);
std::cout << rpsoptions[i] << std::endl;
}

Note that I've glossed over the issue of seeding the pseudo-random number generator; that's covered in the first answer at the link above, and would result in a bunch more code. It's important when you actually want to rely on properties of your random distribution, but not so important to illustrate the way you use the (pseudo-)randomly-generated index.



Related Topics



Leave a reply



Submit