Reputation: 3132
I have an array a = [3,6,774,24,56,2,64,56,34]
. I need to find the second largest number in a single iteration using Ruby. How do I achieve it?
Upvotes: 4
Views: 13375
Reputation: 1
For me this worked:
data_array5 = [45,65632,232,34345,343,23,23,56]
puts data_array5.sort[data_array5.length()-2]
This is generic you replace 2 with any n number to get nth maxmium
Upvotes: 0
Reputation: 193
For me,
a = [3,6,774,24,56,2,64,56,34]
a.uniq # create a new array with the only unique value
a.sort[-2] # find the second greatest value
Upvotes: 1
Reputation: 67850
Just for fun, this method gets the Nth greatest value in a enumerable (you'd use a bisect module to make the insertion into acc
more efficient). As pointed out by @Victor, you would only use it when the length of the array is much bigger than n, othersize a simple array.sort[-n]
is faster.
module Enumerable
def max_nth(n)
inject([]) do |acc, x|
(acc + [x]).sort[[acc.size-(n-1), 0].max..-1]
end.first
end
end
p [1, 5, 2, 32, 2, 41, 15, 55].max_nth(2) #=> 41
Upvotes: 1
Reputation: 9225
sort
is probably overkill here, especially for really large arrays. Don't quite understand "single iteration", one line you mean?
a = [3,6,774,24,56,2,64,56,34]
b = a.shift(2).sort
c =
a.inject(b) do |(m2, m), e|
case
when e > m
[m, e]
when e > m2
[e, m]
else
[m2, m]
end
end
c.first #=> 64
Upvotes: 2