How to find the two largest elements in an array with Ruby

1 Answer

0 votes
# A function that finds the two largest elements in an array.
# It returns an array containing the two largest elements in descending order [largest, second_largest],
# or nil if the array has fewer than 2 elements.
def find_two_largest(arr)
  # Guard clause to handle edge cases safely
  return nil if arr.nil? || arr.length < 2

  # max(2) leverages Ruby's built-in, optimized selection algorithm
  arr.max(2)
end

# Complete program execution
if __FILE__ == $0
  # Define the array with the provided data (using Ruby array brackets)
  data = [3, 4, 9, 6, 7, 1, 2, 5]

  # Call our function
  result = find_two_largest(data)

  if result
    puts "Dataset: #{data.inspect}"
    puts "The largest element is: #{result[0]}"
    puts "The second largest element is: #{result[1]}"
    puts "Combined array of top two: #{result.inspect}"
  else
    puts "Error: The collection must contain at least two elements."
  end
end


# run:
#
# Dataset: [3, 4, 9, 6, 7, 1, 2, 5]
# The largest element is: 9
# The second largest element is: 7
# Combined array of top two: [9, 7]
#

 



answered 15 hours ago by avibootz
...