Ruby :: Aufgabe #4 :: Lösung #4

5 Lösungen Lösungen öffentlich
#4

Funktion welche Minimum und Maximum aus einem Array zurückgibt

Anfänger - Ruby von Gustl - 07.12.2012 um 17:36 Uhr
Programmieren Sie eine Funktion welche aus einem Array von Integer-Elementen das Minimum und Maximum zurückgibt.
Als Übergabe-Parrameter wird das Array übergeben.

Testen Sie die Funktion mit 2 Abfragen, bzw. mit 2 verschiedenen Arrays.
Hilfestellung: Sortierverfahren - Wikipedia
#4
vote_ok
von Idef1x (1320 Punkte) - 23.01.2018 um 15:44 Uhr
Quellcode ausblenden Ruby-Code
=begin
 T.y.P. #4
 By Lars I.
 Lines of Code:     13
=end

#========================================================================

def findMin(array)
=begin
 In:
  - array of which the minimum value is searched
    
 Out:
  - minimum value of the given array
  
=end

#Section - CODE
 
 #Section - Declarations
    
    pos_min = 0
    
 #Section - Finding the min value
 
    0.upto(array.length - 1) { |i| array[pos_min] > array[i] ? pos_min = i : "" }
    
 #Section - Output
 
    return array[pos_min]
    
end

#========================================================================

def findMax(array)
=begin
 In:
  - array of which the maximum value is searched
    
 Out:
  - maximum value of the given array
  
=end

#Section - CODE
 
 #Section - Declarations
    
    pos_max = 0
    
 #Section - Finding the max value
    
    0.upto(array.length - 1) { |i| array[pos_max] < array[i] ? pos_max = i : "" }
    
 #Section - Output
    
    return array[pos_max]
    
end

arr = []
1 .upto(100) { arr.push(rand(100000000) + 1) }

print "array #{arr}\nThe minimum value:\t#{findMin(arr)}\nThe maximum value:\t#{findMax(arr)}"

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben