authorgravatar for andrew@raindev.ioAndrew Barchuk <andrew@raindev.io> 2024-10-05 17:36:54+02:00
committergravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2025-03-26 15:41:14+01:00
log0d65b014ea948df973bb3be227ab9b28ebf36ee4
treeaa86fa35a59e84443de0876bbaabe46f901328c4
parent27f3e8b61db897f36c704c50c86c31b824297d30
signaturebadge-check Signed by SSH key SHA256:7B/LJ7bpR1eX8aCXSr4mtd5M45VMPKcx9zY8e95b5QM

Clarify the multidimensional array example

Use a rectangular matrix instead of a square one to distinguish rows and columns more clearly. Extend the example with row access.

1 files changed, 13 insertions(+), 9 deletions(-)

doc/langref/test_multidimensional_arrays.zig+13-9
...@@ -1,18 +1,22 @@...@@ -1,18 +1,22 @@
1const std = @import("std");1const std = @import("std");
2const expect = std.testing.expect;2const expect = std.testing.expect;
3const expectEqual = std.testing.expectEqual;
34
4const mat4x4 = [4][4]f32{5const mat4x5 = [4][5]f32{
5 [_]f32{ 1.0, 0.0, 0.0, 0.0 },6 [_]f32{ 1.0, 0.0, 0.0, 0.0, 0.0 },
6 [_]f32{ 0.0, 1.0, 0.0, 1.0 },7 [_]f32{ 0.0, 1.0, 0.0, 1.0, 0.0 },
7 [_]f32{ 0.0, 0.0, 1.0, 0.0 },8 [_]f32{ 0.0, 0.0, 1.0, 0.0, 0.0 },
8 [_]f32{ 0.0, 0.0, 0.0, 1.0 },9 [_]f32{ 0.0, 0.0, 0.0, 1.0, 9.9 },
9};10};
10test "multidimensional arrays" {11test "multidimensional arrays" {
12 // mat4x5 itself is a one-dimensional array of arrays.
13 try expectEqual(mat4x5[1], [_]f32{ 0.0, 1.0, 0.0, 1.0, 0.0 });
14
11 // Access the 2D array by indexing the outer array, and then the inner array.15 // Access the 2D array by indexing the outer array, and then the inner array.
12 try expect(mat4x4[1][1] == 1.0);16 try expect(mat4x5[3][4] == 9.9);
1317
14 // Here we iterate with for loops.18 // Here we iterate with for loops.
15 for (mat4x4, 0..) |row, row_index| {19 for (mat4x5, 0..) |row, row_index| {
16 for (row, 0..) |cell, column_index| {20 for (row, 0..) |cell, column_index| {
17 if (row_index == column_index) {21 if (row_index == column_index) {
18 try expect(cell == 1.0);22 try expect(cell == 1.0);
...@@ -20,8 +24,8 @@ test "multidimensional arrays" {...@@ -20,8 +24,8 @@ test "multidimensional arrays" {
20 }24 }
21 }25 }
2226
23 // initialize a multidimensional array to zeros27 // Initialize a multidimensional array to zeros.
24 const all_zero: [4][4]f32 = .{.{0} ** 4} ** 4;28 const all_zero: [4][5]f32 = .{.{0} ** 5} ** 4;
25 try expect(all_zero[0][0] == 0);29 try expect(all_zero[0][0] == 0);
26}30}
2731