Menu
CoddyTech

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 7

Rows, 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) # 12

Neighbors. 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 icon

Challenge

Easy

Write 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:

  1. Main diagonal: and the cells where the row index equals the column index
  2. Anti-diagonal: and the cells from the top-right to the bottom-left corner
  3. Top row: and the first row
  4. Bottom row: and the last row
  5. Left column: and the first column, from top to bottom
  6. Right 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 16

The 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
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