From 386361564bc525eb53c335a66d5cc99e11e4b6b7 Mon Sep 17 00:00:00 2001 From: Artem Darius Weber Date: Sat, 2 Nov 2024 10:39:05 +0300 Subject: [PATCH] Implement methods to find minimum, first positive index, and first positive element with for and while loops --- lab1/src/05_number_items_operations.rb | 68 ++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 lab1/src/05_number_items_operations.rb diff --git a/lab1/src/05_number_items_operations.rb b/lab1/src/05_number_items_operations.rb new file mode 100644 index 0000000..4308a4f --- /dev/null +++ b/lab1/src/05_number_items_operations.rb @@ -0,0 +1,68 @@ + + +def find_min_element_for(arr) + min_element = arr[0] + for element in arr + min_element = element if element < min_element + end + min_element +end + + +def find_min_element_while(arr) + min_element = arr[0] + index = 0 + while index < arr.size + min_element = arr[index] if arr[index] < min_element + index += 1 + end + min_element +end + + +def find_first_positive_index_for(arr) + for index in 0...arr.size + return index if arr[index] > 0 + end + nil +end + + +def find_first_positive_index_while(arr) + index = 0 + while index < arr.size + return index if arr[index] > 0 + index += 1 + end + nil +end + + +def find_first_positive_for(arr) + for element in arr + return element if element > 0 + end + nil +end + + +def find_first_positive_while(arr) + index = 0 + while index < arr.size + return arr[index] if arr[index] > 0 + index += 1 + end + nil +end + +# INPUT +array = [-10, -5, 0, 3, 5, -2] + +puts "Минимальный элемент (for): #{find_min_element_for(array)}" +puts "Минимальный элемент (while): #{find_min_element_while(array)}" + +puts "Индекс первого положительного элемента (for): #{find_first_positive_index_for(array)}" +puts "Индекс первого положительного элемента (while): #{find_first_positive_index_while(array)}" + +puts "Первый положительный элемент (for): #{find_first_positive_for(array)}" +puts "Первый положительный элемент (while): #{find_first_positive_while(array)}"