summaryrefslogtreecommitdiff
path: root/src/day03.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/day03.zig')
-rw-r--r--src/day03.zig63
1 files changed, 63 insertions, 0 deletions
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});
+}