From a50ef4122ea1f1ff3429fbc23c03020cd2f8cfb4 Mon Sep 17 00:00:00 2001 From: Artem Darius Weber Date: Fri, 29 Nov 2024 15:44:17 +0300 Subject: [PATCH] feat: add elements_between_first_and_second_max function to retrieve elements between first and second maximum values --- lab3_task1_funcation_block_arg/main.rb | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/lab3_task1_funcation_block_arg/main.rb b/lab3_task1_funcation_block_arg/main.rb index 676b966..ebf0a59 100644 --- a/lab3_task1_funcation_block_arg/main.rb +++ b/lab3_task1_funcation_block_arg/main.rb @@ -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(", ")