Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a particular function to retrieve then delete random array element?

Tags:

ruby

I know I can do this in a couple of steps, but was wondering if there is a function which can achieve this.

I want to array#sample, then remove the element which was retrieved.

like image 1000
Damien Roche Avatar asked Jun 11 '12 22:06

Damien Roche


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.

Which function is used to delete array elements?

shift() function: This method is use to remove elements from the start of an array.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.


Video Answer


2 Answers

How about this:

array.delete_at(rand(array.length))
like image 145
Linuxios Avatar answered Sep 25 '22 20:09

Linuxios


Another inefficient one, but super obvious what's going on:

array.shuffle.pop

What would be nice would be a destructive version of the sample method on Array itself, something like:

class Array
  def sample!
    delete_at rand length
  end
end
like image 39
micapam Avatar answered Sep 25 '22 20:09

micapam