From 362b2c2cef3e83f115153b10df161f8ad758d64c Mon Sep 17 00:00:00 2001 From: xeals Date: Sat, 2 Dec 2023 18:36:30 +1100 Subject: [PATCH] day02: solve --- src/day02.zig | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/day02.zig diff --git a/src/day02.zig b/src/day02.zig new file mode 100644 index 0000000..150a5c7 --- /dev/null +++ b/src/day02.zig @@ -0,0 +1,94 @@ +const std = @import("std"); + +pub fn main() !void { + const input = @embedFile("data/day02.txt"); + const target = Game{ .red = 12, .green = 13, .blue = 14 }; + const sln = try solve(input, target); + + std.debug.print("{d}\n", .{sln.possible}); + std.debug.print("{d}\n", .{sln.powers}); +} + +const Day02Error = error{ + MissingColon, +}; + +const Game = struct { + red: u32 = 0, + blue: u32 = 0, + green: u32 = 0, + + fn parse(line: []const u8) !@This() { + var self = @This(){}; + var n: u32 = 0; + + const colon = std.mem.indexOfScalar(u8, line, ':') orelse return Day02Error.MissingColon; + var it = std.mem.splitAny(u8, line[colon + 1 ..], ",; "); + while (it.next()) |item| { + if (item.len == 0) { + continue; + } + + switch (item[0]) { + 'r' => self.red = @max(self.red, n), + 'g' => self.green = @max(self.green, n), + 'b' => self.blue = @max(self.blue, n), + '0'...'9' => n = try std.fmt.parseInt(u8, item, 10), + else => unreachable, + } + } + + return self; + } + + fn possible(self: @This(), other: @This()) bool { + return self.red <= other.red and self.green <= other.green and self.blue <= other.blue; + } +}; + +const Solution = struct { + possible: u32, + powers: u32, +}; + +fn solve(input: []const u8, target: Game) !Solution { + var possible: u32 = 0; + var powers: u32 = 0; + + var index: u32 = 1; + var line_it = std.mem.splitScalar(u8, input, '\n'); + while (line_it.next()) |line| : (index += 1) { + if (line.len == 0) { + continue; + } + + const game = try Game.parse(line); + if (game.possible(target)) { + possible += index; + } + powers += game.red * game.blue * game.green; + } + + return Solution{ .possible = possible, .powers = powers }; +} + +fn solveSample() !Solution { + const input = + \\Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green + \\Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue + \\Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red + \\Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red + \\Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green + ; + return solve(input, .{ .red = 12, .blue = 14, .green = 13 }); +} + +test "silver" { + const sln = try solveSample(); + try std.testing.expectEqual(@as(u32, 8), sln.possible); +} + +test "gold" { + const sln = try solveSample(); + try std.testing.expectEqual(@as(u32, 2286), sln.powers); +}