Nested Loops with 2D Arrays
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 14 of 78.
To visit every cell of a 2D array, put one loop inside another. The outer loop goes through the rows, and the inner loop goes through the cells of the current row:
var grid := [[1, 2, 3], [4, 5, 6]]
var total := 0
for row in grid:
for cell in row:
total += cell
print(total) # 21When you need the position of each cell, loop over the indices. r is the row index, c the column index, and the inner loop uses grid[r].size(), the length of the current row:
for r in range(grid.size()):
for c in range(grid[r].size()):
grid[r][c] *= 10
print(grid) # [[10, 20, 30], [40, 50, 60]]Assigning to cell in a for cell in row loop does not change the grid, because cell holds a copy of the number. Change cells through their indices, as above.
Nested loops also build a grid. Create a new row inside the outer loop, fill it in the inner loop, then append it:
var town := []
for r in range(3):
var row := []
for c in range(4):
row.append(".")
town.append(row)
town[1][2] = "P"
for row in town:
print("".join(row))....
..P.
....The row must be created inside the outer loop. An array is shared, not copied, when you append it: if you append the same row three times, the three rows are one array, and town[1][2] = "P" puts a P in every row.
Challenge
EasyDraw the map of a town. The program reads four whole numbers, one per line: the number of rows, the number of columns, the row of the player and the column of the player. The player position is always inside the map.
- Build
grid, a 2D array with that many rows and columns, where every cell is".". Use nested loops, and create a new row array for each row. - Set the cell at the player position to
"P". - Print the map, one row per line, with no spaces between the cells.
For the inputs 3, 4, 1 and 2, the output is:
....
..P.
....Try it yourself
extends Node
func _ready():
var rows := int(OS.read_string_from_stdin())
var cols := int(OS.read_string_from_stdin())
var player_row := int(OS.read_string_from_stdin())
var player_col := int(OS.read_string_from_stdin())
var grid := []
# Build the grid with nested loops
# Put the player on the map
# Print the map
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