From 7b47337e40672c4c5f12a2773d3888c17237f36a Mon Sep 17 00:00:00 2001 From: Xander Bil Date: Wed, 4 Dec 2024 23:58:20 +0100 Subject: solutions day3 and 4 --- src/day03.zig | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/day03.zig (limited to 'src/day03.zig') diff --git a/src/day03.zig b/src/day03.zig new file mode 100644 index 0000000..0a5e27e --- /dev/null +++ b/src/day03.zig @@ -0,0 +1,63 @@ +const std = @import("std"); +const mecha = @import("mecha"); +const print = std.debug.print; + +pub fn solve(part: []u8, buffer: []u8, allocator: std.mem.Allocator) !void { + if (std.mem.eql(u8, part, "1")) { + try part1(buffer, allocator); + } else { + try part2(buffer, allocator); + } +} + +fn part1(buffer: []const u8, allocator: std.mem.Allocator) !void { + const mul = mecha.combine(.{ mecha.string("mul(").discard(), mecha.int(usize, .{}), mecha.ascii.char(',').discard(), mecha.int(usize, .{}), mecha.ascii.char(')').discard() }); + + var sum: usize = 0; + var rest = buffer; + while (rest.len > 0) { + const result = mul.parse(allocator, rest) catch { + rest = rest[1..]; + continue; + }; + sum += result.value[0] * result.value[1]; + rest = result.rest; + } + + print("{d}", .{sum}); +} + +// UGLY +fn part2(buffer: []const u8, allocator: std.mem.Allocator) !void { + const mul = mecha.combine(.{ mecha.string("mul(").discard(), mecha.int(usize, .{}), mecha.ascii.char(',').discard(), mecha.int(usize, .{}), mecha.ascii.char(')').discard() }); + + const dont = mecha.string("don't()"); + const do = mecha.string("do()"); + + var sum: usize = 0; + var rest = buffer; + var disabled = false; + while (rest.len > 0) { + if (disabled) { + _ = do.parse(allocator, rest) catch { + rest = rest[1..]; + continue; + }; + disabled = false; + } else { + const result = mul.parse(allocator, rest) catch { + const result = dont.parse(allocator, rest) catch { + rest = rest[1..]; + continue; + }; + rest = result.rest; + disabled = true; + continue; + }; + sum += result.value[0] * result.value[1]; + rest = result.rest; + } + } + + print("{d}", .{sum}); +} -- cgit v1.2.3