WIP: comptime experiments

This commit is contained in:
Laurens Miers 2024-09-25 12:20:34 +02:00
parent 7417f01d5d
commit b68855fc2d
10 changed files with 57 additions and 15 deletions

View file

@ -8,6 +8,8 @@
// of it.
//
const print = @import("std").debug.print;
const mem = @import("std").mem;
const fmt = @import("std").fmt;
const TripError = error{ Unreachable, EatenByAGrue };
@ -49,12 +51,47 @@ const Path = struct {
//
// Please fill in the body of this function!
fn makePath(from: *Place, to: *Place, dist: u8) Path {
return Path{
.from = from,
.to = to,
.dist = dist,
};
}
fn makePath2(comptime path: []const u8) Path {
var it = mem.split(u8, path, "->");
var from: []const u8 = it.first();
it = mem.split(u8, it.next().?, ":");
var to: []const u8 = it.first();
var dist: []const u8 = it.next().?;
return Path{
.from = &@field(@This(), from),
.to = &@field(@This(), to),
.dist = try fmt.parseInt(u8, dist, 10),
};
}
fn makePath3(comptime path: []const u8) Path {
var it = mem.split(u8, path, "->");
var from: []const u8 = it.first();
var list = it.next().?;
var connections_it = mem.split(u8, list[1..(path.len - from.len - 3)], " ");
while (connections_it.next()) |connect| {
var connection_it = mem.split(u8, connect, ":");
return Path{
.from = &@field(@This(), from),
.to = &@field(@This(), connection_it.first()),
.dist = try fmt.parseInt(u8, connection_it.next().?, 10),
};
}
}
// Using our new function, these path definitions take up considerably less
// space in our program now!
const a_paths = [_]Path{makePath(&a, &b, 2)};
// const a_paths = [_]Path{makePath(&a, &b, 2)};
const a_paths = [_]Path{makePath2("a->b:2")};
// const a_paths = makePath3("a->(b:2)");
const b_paths = [_]Path{ makePath(&b, &a, 2), makePath(&b, &d, 1) };
const c_paths = [_]Path{ makePath(&c, &d, 3), makePath(&c, &e, 2) };
const d_paths = [_]Path{ makePath(&d, &b, 1), makePath(&d, &c, 3), makePath(&d, &f, 7) };
@ -154,6 +191,10 @@ pub fn main() void {
const start = &a; // Archer's Point
const destination = &f; // Fox Pond
// makePath3("a->(b:2 d:3)");
var temp: Path = makePath3("a->(b:2)");
_ = temp;
// We could either have this:
//
// a.paths = a_paths[0..];