feat: add elements_between_first_and_second_max function to retrieve elements between first and second maximum values

lab3
Artem-Darius Weber 1 month ago
parent 44e77f3679
commit a50ef4122e

@ -1,11 +1,36 @@
def indices_sorted_by_descending_values(array)
indices = array.each_with_index.to_a
sorted_indices = indices.sort_by { |(element, index)| -element }
result = sorted_indices.map { |(element, index)| index }
result
end
def elements_between_first_and_second_max(array)
max_value = array.max
max_indices = array.each_with_index.select { |element, index| element == max_value }.map { |_, index| index }
if max_indices.size >= 2
first_max_index = max_indices[0]
second_max_index = max_indices[1]
else
second_max_value = array.select { |element| element != max_value }.max
return [] if second_max_value.nil?
first_max_index = array.index(max_value)
second_max_index = array.index(second_max_value)
end
first_max_index, second_max_index = [first_max_index, second_max_index].sort
array[(first_max_index + 1)...second_max_index]
end
# Ex
array = [5, 3, 8, 1, 7]
puts "Indices in order of decreasing elements:"
puts indices_sorted_by_descending_values(array).join(", ")
array = [5, 1, 8, 3, 8, 7]
puts "Elements between first and second maximum:"
puts elements_between_first_and_second_max(array).join(", ")

Loading…
Cancel
Save