Improve part 1 efficiency

This commit is contained in:
ktkk 2025-12-02 12:22:28 +00:00
parent 45b25120e0
commit 89d248d3b8

View file

@ -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;
}