Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking 2 random elements from array

What is the most efficient way to select 2 unique random elements from an array (ie, make sure the same element is not selected twice).

I have so far:

var elem1;
var elem2;

elem1 = elemList[Math.ceil(Math.random() * elemList.length)];
do {
  elem2 = elemList[Math.ceil(Math.random() * elemList.length)];
} while(elem1 == elem2)

But this often hangs my page load.

Any better solution?

Extra question, how do I extend this to n elements

like image 252
zsquare Avatar asked Mar 15 '12 12:03

zsquare


People also ask

How do you select two random elements from an array?

To get multiple random elements from an array, use the sort() method on the array to shuffle the array elements in a random order, e.g. arr. sort(() => 0.5 - Math. random()) . Then call the slice() method on the shuffled array to get multiple random elements.

Can we access elements randomly in an array?

random. choice() function is used to get random elements from a NumPy array. It is a built-in function in the NumPy package of python.

How do I find the second element of an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.


2 Answers

do NOT use loops and comparisons. Instead

  • shuffle the array
  • take first two elements
like image 132
georg Avatar answered Sep 28 '22 08:09

georg


It can be done using built-in functionality (slice and sort),

var n = 2
    randomItems = array.sort(() => .5 - Math.random()).slice(0, n);
like image 26
Mehdi Dehghani Avatar answered Sep 28 '22 08:09

Mehdi Dehghani