rubyist
rubyist

Reputation: 3132

Find second largest number from an array in Ruby

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

Answers (8)

Saim Malik
Saim Malik

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

Jay lahari
Jay lahari

Reputation: 1

array = [1,2,3,4,5,6]
puts array.max(2).last

Upvotes: -1

yosefbennywidyo
yosefbennywidyo

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

ramin
ramin

Reputation: 1

It works too:

arr.sort.reverse[1]

Upvotes: 0

tomios
tomios

Reputation: 31

This works, but am not sure for the "single iteration"

a.max(2)[1]

Upvotes: 3

tokland
tokland

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

Victor Moroz
Victor Moroz

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

Maurício Linhares
Maurício Linhares

Reputation: 40333

Simple:

array.sort[-2]

And you're done :)

Upvotes: 19

Related Questions