You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kubsu-sm5-ruby/lab3_task1_funcation_block_arg/main.rb

51 lines
1.6 KiB

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
def elements_between_first_and_last_max(array)
max_value = array.max
first_max_index = array.index(max_value)
last_max_index = array.rindex(max_value)
return [] if first_max_index == last_max_index
first_max_index, last_max_index = [first_max_index, last_max_index].sort
array[(first_max_index + 1)...last_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(", ")
array = [5, 1, 8, 3, 7, 8]
puts "Elements between first and last maximum:"
puts elements_between_first_and_last_max(array).join(", ")