Jagged Arrays
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 16 of 78.
The rows of a 2D array do not need the same length. A 2D array whose rows have different lengths is a jagged array. Here each row holds the scores of one player, and the players have played a different number of rounds:
var scores := [
[90, 85, 70],
[60],
[75, 80]
]
print(scores[0].size()) # 3
print(scores[1].size()) # 1In a jagged array, scores[0].size() is not the length of every row. Loop over the columns of the current row with scores[r].size():
for r in range(scores.size()):
var total := 0
for c in range(scores[r].size()):
total += scores[r][c]
print("Player ", r + 1, ": ", total)Player 1: 245
Player 2: 60
Player 3: 155A loop that always uses the length of the first row reads past the end of the shorter rows: scores[1][2] is an error, because row 1 has only index 0. for value in row always fits the row it walks through.
You build a jagged array like a grid, with a different length for each row. In this triangle, row r has r + 1 cells:
var triangle := []
for r in range(4):
var row := []
for c in range(r + 1):
row.append("*")
triangle.append(row)
for row in triangle:
print("".join(row))*
**
***
****A row can even be empty: [[1, 2], [], [3]] is a valid jagged array with three rows.
Challenge
EasyWrite a function named make_triangle with one int parameter n. It returns a jagged array of n rows:
- Row 1 has 1 cell, row 2 has 2 cells, and so on, until row
n, which hasncells. - Counting rows and columns from 1, each cell holds its row number times its column number. The cell in row 3, column 2 holds
3 * 2 = 6.
For example, make_triangle(3) returns:
[[1], [2, 4], [3, 6, 9]]The tests call make_triangle() themselves and check the returned array. Do not call it and do not print anything.
Try it yourself
func make_triangle(n: int):
# Write code here
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler