How to Randomly Pick an Element from an Array

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];
}

Get a random item from a JavaScript array

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

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 Choose an Element from an Array that Wasn't Chosen before in JavaScript?

You can try something like this:

Idea

  • Create a utility function that takes an array and returns you a random value.
  • Inside this Array, maintain 2 array, choices and data.
  • In every iteration, remove 1 item from data and put it in chosenItems
  • Once the length of data reaches 0, set chosenItems or originalArray as data and repeat process.

Benefit of this approach would be,

  • You dont need to maintain and pass array variable.
  • It can be made generic and used multiple times.

function randomize(arr) {
let data = [...arr];
let chosenItems = [];

function getRandomValue() {
if (data.length === 0) {
data = chosenItems;
chosenItems = [];
}
const index = Math.floor(Math.random() * data.length);
const choice = data.splice(index, 1)[0];

chosenItems.push(choice);
return choice;
}

return {
randomItem: getRandomValue
}
}

const dummyData = [ 1,2,3,4,5 ];

const randomizeData = randomize(dummyData);

for (let i = 0; i< 10; i++) {
console.log(randomizeData.randomItem())
}

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]);

Pick a random element from an array

Swift 4.2 and above

The new recommended approach is a built-in method on the Collection protocol: randomElement(). It returns an optional to avoid the empty case I assumed against previously.

let array = ["Frodo", "Samwise", "Merry", "Pippin"]
print(array.randomElement()!) // Using ! knowing I have array.count > 0

If you don't create the array and aren't guaranteed count > 0, you should do something like:

if let randomElement = array.randomElement() { 
print(randomElement)
}

Swift 4.1 and below

Just to answer your question, you can do this to achieve random array selection:

let array = ["Frodo", "Samwise", "Merry", "Pippin"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

The castings are ugly, but I believe they're required unless someone else has another way.

Can I pick a random element from an array in C++?

rand() is a pseudo random number generator. That means, given the same starting conditions (seed), it will generate the same pseudo random sequence of numbers every time.

So, change the seed for the random number generator (e.g. use the current time as a starting condition for the random number generator).

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

static const string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};

int main() {
//variables moved to inside main()
string guess;
int lives = 3;

srand(time(NULL));
string word = words[rand() % 6];

How do I randomly pick elements from an Array that satisfy a condition?

Before choosing randomly, filter the array with:

Players [] health_players = Arrays.stream(this.putIntoList())
.filter(i -> i.getHealth() > 0)
.toArray();

only then choose randomly from the health_players.

Random myNumber = new Random();
public Player pickOutAndReturn(){
Players [] health_players = Arrays.stream(this.putIntoList())
.filter(i -> i.getHealth() > 0)
.toArray();

int anotherNumber = myNumber.nextInt(health_players.length);
return health_players[anotherNumber];
}

How to randomly pick element from an array with different probabilities in C++

You are looking for std::discrete_distribution. Forget about rand().

#include <random>
#include <vector>

struct Point {};

int main() {
std::mt19937 gen(std::random_device{}());

std::vector<double> chances{1.0, 2.0, 3.0};
// Initialize to same length.
std::vector<Point> points(chances.size());
// size_t is suitable for indexing.
std::discrete_distribution<std::size_t> d{chances.begin(), chances.end()};

auto sampled_value = points[d(gen)];
}

Conveniently for you, the weights do not have to sum to 1.



Related Topics



Leave a reply



Submit