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