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.
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.
shift() function: This method is use to remove elements from the start of an array.
Most efficient way to remove an element from an array, then reduce the size of the array.
How about this:
array.delete_at(rand(array.length))
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
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