Two Strategies

There are two strategies for arranging items in a grid:

  1. Use a single loop to iterate over the number of items; derive the x and y position from the item number.

    Screenshot of Notion (4-8-22, 12-57-55 AM).png

  2. Use a nested loop to iterate over the x positions and, for each x, iterate over the y positions (left sketches). If the item number is required, derive it from the values of x and y (right sketch).

    Screenshot of Microsoft Edge (4-8-22, 1-02-54 AM).png

Strategy 1: Deriving the x and y positions from the index

Review: Arranging items in a line

This builds on Arranging a Line of Items. Here is a sketch from that page:

function setup() {
	createCanvas(windowWidth, windowHeight);
}

function draw() {
	for (let i = 0; i < 30; i++) {
		let x = 20 + 50 * i;
		circle(x, 100, 40);
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/11da5255-53dc-4366-b2a6-5732f42a2526/Untitled.png

The shape position is derived from the loop index, using the function $x = 10 + 50i$ used here.

Note: From here on, the definition of setup() is not shown. Each of the following code samples assumes that the sketch also contains a setup() function:

function setup() {
	createCanvas(windowWidth, windowHeight);
}

Derive y from i as well.

function draw() {
	for (let i = 0; i < 30; i++) {
		let x = 30 + 50 * i;
		let y = 30 + 10 * i;
		circle(x, y, 40);
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a1a95c66-9c10-445c-8724-75e5e30a5ce2/Untitled.png

Deriving the column (x position)

Let’s start with the angled line from above, and just look at the x position.

function draw() {
	for (let i = 0; i < 30; i++) {
		let x = 30 + 50 * i;
		let y = 30 + 50 * i;
		circle(x, y, 20);
	}
}

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/79a442fe-45f2-489c-b7f1-bb31505c9998/Untitled.png

Instead of a diagonal line, where each x is greater than the previous x and each y is greater than the previous y, we would like to arrange the items on a grid. Here, each item is labelled with its index number. The x value increases from items 0 to 4, and then it resets back to the left side and increases again to 9, and so on.

Screenshot of Safari (4-8-22, 12-44-58 AM).png

We can use the modulo (remainder) operator % to chop it into pieces. For an input sequence i = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 etc., the modulo operator i % 5 produces 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, etc. The sketch then multiples this by 50 to make the result more visible: 0, 50, 100, 150, 200, 0, 50, 100, 150, 200, 0, 50, etc.