Menu
CoddyTech

Finding Minimum and Maximum

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 50 of 78.

Arrays have the methods min() and max(), which return the smallest and the largest element:

var temps := [18, 25, 9, 31, 22]
print(temps.min()) # 9
print(temps.max()) # 31

The global functions min() and max() compare the numbers you pass them, which is handy for two or three values:

print(max(4, 12, 7)) # 12
var hp: int = min(120, 100) # 100, never above 100

Strings are compared character by character, by their Unicode code. Every capital letter comes before every lowercase letter:

var words := ["kiwi", "apple", "Fig"]
print(words.min()) # Fig
print(words.max()) # kiwi

The same rule applies to numbers stored as text: "9" is larger than "56", because the character 9 comes after 5. Convert input with int() before you compare numbers.

On an empty array, both methods return null. To find where the largest value is, pass it to find(): temps.find(temps.max()) is 3. For a dictionary, take the largest of its values and look up its key with find_key(), which returns the first key with that value:

var scores := {"Mia": 120, "Leo": 95, "Ana": 140}
var best: int = scores.values().max()
print(scores.find_key(best), " ", best) # Ana 140

max() returns a value of any type, so declare the type of the variable (var best: int) instead of writing :=.

challenge icon

Challenge

Easy

The program reads two lines: whole numbers separated by spaces, and words separated by spaces. Each line has at least one value.

Print the smallest and the largest number, then the smallest and the largest word, with min() and max(). Compare the numbers as numbers, not as text. For the inputs 42 17 23 56 9 34 and kiwi apple banana cherry date, the output is:

Smallest number: 9
Largest number: 56
Smallest word: apple
Largest word: kiwi

Try it yourself

extends Node

func _ready():
	var number_texts := OS.read_string_from_stdin().split(" ", false)
	var words := Array(OS.read_string_from_stdin().split(" ", false))
	# Convert the numbers to int, then print the four results
	pass
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler