Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find, return and remove the maximum value from an array in Ruby?

Tags:

arrays

ruby

I would like to find the max value in an array of integers, return that value, and remove it from the array. Is there a built in function for this?

For a = [1,2,3,4], I can easily do this a.max which returns 4. However, a[....] remains unchanged.

like image 525
malexanders Avatar asked Dec 30 '25 21:12

malexanders


2 Answers

You could do something like this.

a = [1,2,3,4]
a.delete(a.max)
=> 4
a => [1, 2, 3]

To delete a single instance if there are duplicates you could use something like (As per the comments, use a.index(a.max) to get the index of the max value)

a = [1, 2, 3, 4, 4]
a.delete_at(a.index(a.max))
=> 4
a => [1, 2, 3, 4]
like image 158
user3366016 Avatar answered Jan 02 '26 11:01

user3366016


Benchmarks:

require 'fruity'

ARY = (0..99).to_a.shuffle

compare do
  matthewalexander { a = ARY.dup; a.delete_at(a.index(a.max)) }
  sagarpandya82    { a = ARY.dup; a.sort!.pop                 }
end

# >> Running each test 512 times. Test will take about 1 second.
# >> sagarpandya82 is faster than matthewalexander by 10.000000000000009% ± 10.0%

Increasing the size of ARY will change the results:

ARY = (0..999_999).to_a.shuffle

compare do
  matthewalexander { a = ARY.dup; a.delete_at(a.index(a.max)) }
  sagarpandya82    { a = ARY.dup; a.sort!.pop                 }
end

# >> Running each test once. Test will take about 5 seconds.
# >> matthewalexander is faster than sagarpandya82 by 3x ± 0.1

Use the appropriate approach for your given needs. If you don't know the size of the array I'd recommend assuming your data will grow since they're so close with small arrays.

like image 23
the Tin Man Avatar answered Jan 02 '26 11:01

the Tin Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!