diff --git a/day4_p1.zig b/day4_p1.zig new file mode 100644 index 0000000..8ab05e1 --- /dev/null +++ b/day4_p1.zig @@ -0,0 +1,36 @@ +// Hey puzzle designer, why ???? +const std = @import("std"); + +pub fn main() !void { + const stdin = std.io.getStdIn(); + var buf_io = std.io.bufferedReader(stdin.reader()); + var reader = buf_io.reader(); + + var buf = [_]u8{0} ** 100; + _ = try reader.readAll(&buf); + + const stripped = std.mem.trim(u8, &buf, " \n\r\x00"); + const solution = try mine(stripped); + std.debug.print("{d}", .{solution}); +} + +fn mine(key: []const u8) !u64 { + var buf = [_]u8{0} ** 10000; + for (1..1e10) |i| { + const candidate = try std.fmt.bufPrintZ(&buf, "{s}{d}", .{ key, i }); + var result = [_]u8{0} ** std.crypto.hash.Md5.digest_length; + std.crypto.hash.Md5.hash(candidate, &result, .{}); + + // Check first 5 zeroes (2 bytes and.. a half) + if (result[0] == 0 and result[1] == 0 and result[2] < 0x10) { + return i; + } + } + + return 0; +} + +test "day-test" { + try std.testing.expectEqual(try mine("abcdef"), 609043); + try std.testing.expectEqual(try mine("pqrstuv"), 1048970); +} diff --git a/day4_p2.zig b/day4_p2.zig new file mode 100644 index 0000000..52c3417 --- /dev/null +++ b/day4_p2.zig @@ -0,0 +1,31 @@ +// Hey puzzle designer, why ???? +const std = @import("std"); + +pub fn main() !void { + const stdin = std.io.getStdIn(); + var buf_io = std.io.bufferedReader(stdin.reader()); + var reader = buf_io.reader(); + + var buf = [_]u8{0} ** 100; + _ = try reader.readAll(&buf); + + const stripped = std.mem.trim(u8, &buf, " \n\r\x00"); + const solution = try mine(stripped); + std.debug.print("{d}", .{solution}); +} + +fn mine(key: []const u8) !u64 { + var buf = [_]u8{0} ** 10000; + for (1..1e10) |i| { + const candidate = try std.fmt.bufPrintZ(&buf, "{s}{d}", .{ key, i }); + var result = [_]u8{0} ** std.crypto.hash.Md5.digest_length; + std.crypto.hash.Md5.hash(candidate, &result, .{}); + + // Check first 6 zeroes (3 bytes) + if (result[0] == 0 and result[1] == 0 and result[2] == 0) { + return i; + } + } + + return 0; +}