malexanders
malexanders

Reputation: 3343

How to find, return and remove the maximum value from an array in 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.

Upvotes: 3

Views: 4502

Answers (4)

the Tin Man
the Tin Man

Reputation: 160551

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.

Upvotes: 4

user3366016
user3366016

Reputation: 1312

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]

Upvotes: 7

malexanders
malexanders

Reputation: 3343

This works:

a.delete_at(a.index(a.max))

Upvotes: 0

Sagar Pandya
Sagar Pandya

Reputation: 9497

This should do the trick:

a.sort!.pop #=> 4

Upvotes: 2

Related Questions