Common 2D Array Patterns
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 17 of 78.
A few ways of walking through a grid come up again and again. These examples use a square grid of size n:
var grid := [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
var n := grid.size()Diagonals. On the main diagonal, the row index equals the column index: grid[i][i]. On the anti-diagonal, from the top-right corner to the bottom-left one, the column is n - 1 - i. One loop is enough:
for i in range(n):
print(grid[i][i], " ", grid[i][n - 1 - i])1 3
5 5
9 7Rows, columns and borders. Fix one index and loop over the other. The top row is grid[0] and the bottom row is grid[n - 1]. A column keeps c fixed while the row changes:
var left_total := 0
for r in range(n):
left_total += grid[r][0] # left column: 1 + 4 + 7
print(left_total) # 12Neighbors. In grid games you often look at the cells around a position: up, down, left and right. Store the four steps as an array of [row, column] pairs, and skip the steps that leave the grid:
var r := 0
var c := 1
for step in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
var nr: int = r + step[0]
var nc: int = c + step[1]
if nr >= 0 and nr < n and nc >= 0 and nc < n:
print(grid[nr][nc])The cell grid[0][1] is on the top border, so it has 3 neighbors: 5, 1 and 3.
Challenge
EasyWrite a function named print_patterns with one parameter, grid: a square 2D array of integers (declare it as grid: Array). It prints six lines, with the values separated by single spaces:
Main diagonal:and the cells where the row index equals the column indexAnti-diagonal:and the cells from the top-right to the bottom-left cornerTop row:and the first rowBottom row:and the last rowLeft column:and the first column, from top to bottomRight column:and the last column, from top to bottom
For the grid [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], the output is:
Main diagonal: 1 6 11 16
Anti-diagonal: 4 7 10 13
Top row: 1 2 3 4
Bottom row: 13 14 15 16
Left column: 1 5 9 13
Right column: 4 8 12 16The tests call print_patterns() themselves. Do not call it, and do not return anything.
Try it yourself
func print_patterns(grid: Array):
# 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