diff options
author | Xander Bil <xander@biltopia.org> | 2024-12-04 23:58:20 +0100 |
---|---|---|
committer | Xander Bil <xander@biltopia.org> | 2024-12-04 23:58:20 +0100 |
commit | 7b47337e40672c4c5f12a2773d3888c17237f36a (patch) | |
tree | 734e104dacaeb4708912449aac28a074f225acc5 /src/day03.zig | |
parent | 1c2490f5f2c9419ddb5035fc3a8967beef691e6c (diff) | |
download | aoc2024-7b47337e40672c4c5f12a2773d3888c17237f36a.tar.xz aoc2024-7b47337e40672c4c5f12a2773d3888c17237f36a.zip |
solutions day3 and 4
Diffstat (limited to 'src/day03.zig')
-rw-r--r-- | src/day03.zig | 63 |
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}); +} |