Skip to content

Instantly share code, notes, and snippets.

@wcarron27
Last active May 6, 2025 16:56
Show Gist options
  • Save wcarron27/327f49781ea7c51aaef5d8757864f557 to your computer and use it in GitHub Desktop.
Save wcarron27/327f49781ea7c51aaef5d8757864f557 to your computer and use it in GitHub Desktop.
find_two_highest_values
def find_two_highest_values(array)
highest_indices = []
second_highest_indices = []
return nil unless array.is_a?(Array)
return nil if array.length == 0
return array[0] if array.length == 1
highest_value = array[0]
second_highest_value = nil
array.each_with_index do |val, idx|
if val > highest_value
second_highest_value = highest_value
second_highest_indices = highest_indices
highest_value = val
highest_indices = [idx]
elsif val == highest_value
highest_indices << idx
elsif second_highest_value.nil? || val > second_highest_value
second_highest_value = val
second_highest_indices = [idx]
elsif val == second_highest_value
second_highest_indices << idx
end
end
# {
# highest: highest_indices,
# second_highest: second_highest_indices
# }
result = reduce_values(highest_indices, second_highest_indices)
result
end
# Use whatever logic you want to do the tie-breaking and return the required data structure.
# I left it as-is for simplicity.
def reduce_values(highest, second_highest)
value = {
highest: highest,
second_highest: second_highest
}
value
end
first_array = [1,3,5,7,7,11]
second_array = [1,2,2,3,3,5]
third_array = [1,15,24,13,15]
empty_array = []
not_array = 12
first_result = find_two_highest_values(first_array)
second_result = find_two_highest_values(second_array)
third_result = find_two_highest_values(third_array)
empty_result = find_two_highest_values(empty_array)
not_array_result = find_two_highest_values(not_array)
puts "1st array as arg should return { highest: [5], second_highest: [3, 4] } | Result: #{first_result}"
puts "2nd array as arg should return { highest: [5], second_highest: [3, 4] } | Result: #{second_result}"
puts "3rd array as arg should return { highest: [2], second_highest: [1, 4] } | Result: #{third_result}"
puts "Empty array as arg should return nil | Result: #{empty_result}"
puts "Not array as arg should return nil | Result: #{not_array_result}"
@wcarron27
Copy link
Author

Ruby automatically returns the last variable/ result of expression in a method so that's why value and result are not explicitly returned

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment