Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random element from an array and remove it

Tags:

ruby

I would like to pick an random element from an array, remove it from the array, and then return the element.

I can use sample to get an element, index to find where it is, and then delete_at to remove it, but is there a better way?

like image 654
MxLDevs Avatar asked Jul 20 '13 15:07

MxLDevs


People also ask

How do you remove random items from an array?

We are required to create a function removeRandom() that takes in the array and recursively removes one random item from the array and simultaneously printing it until the array contains items. This can be done through creating a random number using Math. random() and removing the item at that index using Array.

How do I find and remove an element from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.

How do I remove an item from an array by value?

To remove an item from a given array by value, you need to get the index of that value by using the indexOf() function and then use the splice() function to remove the value from the array using its index.


1 Answers

array.delete_at(rand(array.length))

This seems right, and I guess it works best.

EDIT: This same answer is here: Is there a particular function to retrieve then delete random array element? so I'd go with this :D

like image 106
Vrashabh Irde Avatar answered Sep 24 '22 12:09

Vrashabh Irde