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
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.
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.
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.
do NOT use loops and comparisons. Instead
It can be done using built-in functionality (slice and sort),
var n = 2
randomItems = array.sort(() => .5 - Math.random()).slice(0, n);
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