From d5ee0f6aefd94d54c94a4bdce6fd1266f5463c9c Mon Sep 17 00:00:00 2001 From: xeals Date: Fri, 1 Dec 2023 23:57:42 +1100 Subject: [PATCH] day01: include both part 1 and 2 --- src/day01.zig | 52 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/src/day01.zig b/src/day01.zig index 7d66021..cf87bab 100644 --- a/src/day01.zig +++ b/src/day01.zig @@ -3,14 +3,43 @@ const util = @import("util.zig"); pub fn main() !void { const input = @embedFile("data/day01.txt"); - const sln = try solve(input); - std.debug.print("Solution: {d}", .{sln}); + std.debug.print("{d}\n", .{try silver(input)}); + std.debug.print("{d}\n", .{try gold(input)}); +} + +const zero = @as(u8, '0'); + +fn silver(input: []const u8) !u32 { + var sum: u32 = 0; + + var it = std.mem.splitAny(u8, input, "\n"); + while (it.next()) |line| { + if (std.mem.eql(u8, "", line)) { + continue; + } + + var first: u8 = 0; + var last: u8 = 0; + for (line) |char| { + if (char < '0' or char > '9') { + continue; + } + if (first == 0) { + first = char; + } + last = char; + } + + const cal_value = (first - zero) * 10 + (last - zero); + sum += cal_value; + } + + return sum; } const numbers = [_][]const u8{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; -const zero = @as(u8, '0'); -fn solve(input: []const u8) !u32 { +fn gold(input: []const u8) !u32 { var sum: u32 = 0; var it = std.mem.splitAny(u8, input, "\n"); @@ -49,7 +78,18 @@ fn solve(input: []const u8) !u32 { return sum; } -test "sample" { +test "silver" { + const input = + \\1abc2 + \\pqr3stu8vwx + \\a1b2c3d4e5f + \\treb7uchet + ; + const sln = try silver(input); + try std.testing.expectEqual(@as(u32, 142), sln); +} + +test "gold" { const input = \\two1nine \\eightwothree @@ -59,6 +99,6 @@ test "sample" { \\zoneight234 \\7pqrstsixteen ; - const sln = try solve(input); + const sln = try gold(input); try std.testing.expectEqual(@as(u32, 281), sln); }