I have an implementation which has the following function signature:
fn updateMatrix(alloc: std.mem.Allocator, comptime m: usize, comptime n: usize, grid: [m][n]u8) ![m][n]u8 {
// create a copy of `grid`
// modify the copy such that each 1 contains a distance to its nearest 0 (the 0 has to be 4-directionally
// (up, down, left, rigth) adjacent)
// return the updated copy
}
The 2D array grid
consists of 0s and 1s only. The number of rows and columns in grid
could be any positive value in the range [1, 100]
To test the implementation I have unit tests which look like the below (and run correctly):
test "the 1 at (2,1) is at distance 2 from the nearest zeroes, which are (1,0), (1,2), and (0,1)" {
const grid = [3][3]u8{
.{ 0, 0, 0 },
.{ 0, 1, 0 },
.{ 1, 1, 1 },
};
const expected = [3][3]u8{
.{ 0, 0, 0 },
.{ 0, 1, 0 },
.{ 1, 2, 1 },
};
const result = try updateMatrix(testing.allocator, 3, 3, grid);
try testing.expectEqualDeep(expected, result);
}
test "no changes in output - all 1s are already at their respective distance from the nearest 0" {
const grid = [2][3]u8{
.{1, 0, 1},
.{0, 1, 0},
};
const expected = [2][3]u8{
.{1, 0, 1},
.{0, 1, 0},
};
const result = try updateMatrix(testing.allocator, 2, 3, grid);
try testing.expectEqualDeep(expected, result);
}
For other programs, I have table-driven tests with the structure:
test declTest {
const test_case = [_]struct{
description: []const u8,
input: []const u8,
output: []const u8,
}{
.{
.description = "example 1",
.input = &[_]u8{1, 2, 3},
.output = &[_]u8{4, 5, 6},
},
.{
.description = "example 1",
.input = &[_]u8{2, 3, 4},
.output = &[_]u8{5, 6, 7},
},
};
for (test_case) |tc| {
const got = try declTest(tc.input);
const want = tc.output;
std.debug.print("{s}\n", .{tc.description});
try testing.expectEqual(want, got);
}
}
but haven’t used this structure with comptime
yet.
How can I convert the unit tests for updateMatrix
to a table-driven test?