I have the following code for a toy project to learn zig.
const std = @import("std");
const ArrayList = std.ArrayList;
pub const Map = struct {
const Self = @This();
num_locations: usize,
distances: ArrayList(f32),
pub fn init(allocator: std.mem.Allocator, num: usize) !Map {
return .{
.num_locations = num,
.distances = try ArrayList(f32).initCapacity(allocator, num * (num - 1) / 2),
};
}
pub fn deinit(self: Self) void {
self.distances.deinit();
}
pub fn distanceBetween(self: Self, a: usize, b: usize) f32 {
if (b < a) return self.distanceBetween(b, a);
if (a == b) return 0.0;
if (b >= self.num_locations) return std.math.inf(f32);
if (a == 0) return self.distances.items[b - a];
return self.distances.items[a * self.num_locations - a * (a + 1) / 2 + b - a];
}
};
test "distance between" {
const alloc = std.testing.allocator;
var map = try Map.init(alloc, 4);
try map.distances.replaceRange(0, 6, &[_]f32{ 0.1, 0.2, 0.3, 1.2, 1.3, 2.3 });
var i: usize = 0;
while (i < 4) : (i += 1) {
var j: usize = 0;
while (j < 4) : (j += 1) {
if (i == j) {
try std.testing.expectApproxEqRel(0.0, map.distanceBetween(i, j), 1e-9);
} else {
try std.testing.expectApproxEqRel( //
@as(f32, @floatFromInt(@min(i, j))) + 0.1 * @as(f32, @floatFromInt(@max(i, j))), //
map.distanceBetween(i, j), //
1e-9 //
);
}
}
}
}