Finish day01, part 1

This commit is contained in:
ktkk 2025-12-01 22:18:44 +00:00
parent 1a0e6cd0b4
commit 3e7efd4d0a

View file

@ -14,7 +14,11 @@ pub fn run(_: std.mem.Allocator) !void {
while (lines.next()) |line| { while (lines.next()) |line| {
const direction: Direction = if (line[0] == 'L') .left else if (line[0] == 'R') .right else continue; const direction: Direction = if (line[0] == 'L') .left else if (line[0] == 'R') .right else continue;
const amount = try std.fmt.parseUnsigned(u32, line[1..], 10); const amount = try std.fmt.parseUnsigned(u32, line[1..], 10);
try updatePosition(&position, direction, amount, 99);
zero_hits += try updatePosition(&position, direction, amount, 100);
std.debug.print("{s} => {d}\n", .{line, position});
if (position == 0) { if (position == 0) {
zero_hits += 1; zero_hits += 1;
} }
@ -39,7 +43,7 @@ fn updatePosition(
direction: Direction, direction: Direction,
amount: u32, amount: u32,
upper_bound: u32, upper_bound: u32,
) !void { ) !u32 {
var signed_position: i32 = @intCast(position.*); var signed_position: i32 = @intCast(position.*);
switch (direction) { switch (direction) {
@ -51,17 +55,14 @@ fn updatePosition(
}, },
} }
if (signed_position == upper_bound) { if (signed_position > upper_bound - 1 or signed_position < 0) {
position.* = @intCast(signed_position);
} else if (signed_position == 0) {
position.* = 0;
} else if (signed_position > upper_bound or signed_position < 0) {
const signed_upper_bound: i32 = @intCast(upper_bound); const signed_upper_bound: i32 = @intCast(upper_bound);
var mod = @mod(signed_position, signed_upper_bound); const mod = @mod(signed_position, signed_upper_bound);
if (signed_position < 0) mod += 1;
position.* = @intCast(mod); position.* = @intCast(mod);
return 0;
} else { } else {
position.* = @intCast(signed_position); position.* = @intCast(signed_position);
return 0;
} }
} }