aoc2022/day6/puzzle_post_test.zig

57 lines
1.7 KiB
Zig

const std = @import("std");
const input = @embedFile("input");
pub fn main() !void {
// Put this or it doesn't evaluate all branches
@setEvalBranchQuota(500000);
const result = comptime findUniqueCharsIdx(14, input);
const ares = comptime uintEncode(result, 10, "0123456789") catch unreachable;
_ = std.os.linux.write(1, &ares, 10);
}
fn uintEncode(num: usize, comptime bufflen: usize, comptime charset: []const u8) ![bufflen]u8 {
// Check if the number is bigger than the maximum possible number
var pow = comptime std.math.pow(usize, charset.len, bufflen);
if (num >= pow) unreachable;
var buff = [_]u8{charset[0]} ** bufflen;
var num_i: usize = num;
for (buff) |*pos| {
pow /= charset.len;
pos.* = charset[@divTrunc(num_i, pow)];
num_i %= pow;
}
return buff;
}
fn findUniqueCharsIdx(_n: usize, string: []const u8) usize {
for (input) |_, i| {
const n = _n - 1;
// Start searching at fourth character
if (i < n) continue;
if (i > input.len - n) break;
const chars: []const u8 = string[i-n..i+1];
chars: for (chars) |char_1, j| {
for (chars) |char_2, k| {
// Don't check the same character, or the ones that we already checked
if (j <= k) continue;
//std.debug.print("{c},{c}\n", .{char_1, char_2});
if (char_1 == char_2) {
// Don't check anymore
break :chars;
}
}
} else {
// If no repeats have been found
// i is the current character index in the input (i+1 if we count from 1)
return i + 1;
}
}
return 0;
}