From 89d248d3b860f42456a7d34697408fd3141df1db Mon Sep 17 00:00:00 2001 From: ktkk Date: Tue, 2 Dec 2025 12:22:28 +0000 Subject: [PATCH] Improve part 1 efficiency --- src/days/day02.zig | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/src/days/day02.zig b/src/days/day02.zig index 098b80e..8e45652 100644 --- a/src/days/day02.zig +++ b/src/days/day02.zig @@ -2,7 +2,7 @@ const std = @import("std"); pub const title = "Day 02"; -pub fn run(allocator: std.mem.Allocator) !void { +pub fn run(_: std.mem.Allocator) !void { const input = @embedFile("./input/day02.txt"); var ranges = std.mem.tokenizeScalar(u8, input, ','); @@ -18,13 +18,17 @@ pub fn run(allocator: std.mem.Allocator) !void { std.debug.print("{d} to {d}\n", .{start, end}); outer: for (start..end+1) |id| { - const id_s = try std.fmt.allocPrint(allocator, "{}", .{id}); - defer allocator.free(id_s); + // IDs smaller than 10 cannot possibly have repeated digits + if (id / 10 == 0) continue; - if (id_s.len % 2 == 1) continue; + const len = getLen(id); + // Uneven numbers cannot consist of 2 sequences + if (len % 2 == 1) continue; - for (0..id_s.len / 2) |i| { - if (id_s[i] != id_s[i + id_s.len / 2]) { + for (0..len / 2) |i| { + const a = getDigit(id, i); + const b = getDigit(id, i + len / 2); + if (a != b) { continue :outer; } } @@ -41,3 +45,22 @@ pub fn run(allocator: std.mem.Allocator) !void { try stdout.flush(); } +fn getDigit(x: u64, n: usize) u8 { + var new_x = x; + for (0..n) |_| { + new_x /= 10; + } + return @intCast(new_x % 10); +} + +fn getLen(x: u64) usize { + var new_x = x; + var n: usize = 0; + while (true) { + n += 1; + new_x /= 10; + if (new_x == 0) break; + } + return n; +} +