1
0

day01: merge silver/gold solutions
Some checks failed
Build and test / test (push) Failing after 2m53s

This commit is contained in:
xeals 2023-12-02 00:24:26 +11:00
parent d5ee0f6aef
commit 44ccf7b6e2
Signed by: xeals
SSH Key Fingerprint: SHA256:53xHRPqZPQewIgPNiVQ96gm8O4xBVzaxNj1LCSJpTf4

View File

@ -1,45 +1,17 @@
const std = @import("std"); const std = @import("std");
const util = @import("util.zig"); const util = @import("util.zig");
const numbers = [_][]const u8{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
pub fn main() !void { pub fn main() !void {
const input = @embedFile("data/day01.txt"); const input = @embedFile("data/day01.txt");
std.debug.print("{d}\n", .{try silver(input)}); std.debug.print("{d}\n", .{try solve(input, &[_][]u8{})});
std.debug.print("{d}\n", .{try gold(input)}); std.debug.print("{d}\n", .{try solve(input, &numbers)});
} }
const zero = @as(u8, '0'); const zero = @as(u8, '0');
fn silver(input: []const u8) !u32 { fn solve(input: []const u8, words: []const []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" };
fn gold(input: []const u8) !u32 {
var sum: u32 = 0; var sum: u32 = 0;
var it = std.mem.splitAny(u8, input, "\n"); var it = std.mem.splitAny(u8, input, "\n");
@ -56,9 +28,9 @@ fn gold(input: []const u8) !u32 {
if (line[offset] >= '0' and line[offset] <= '9') { if (line[offset] >= '0' and line[offset] <= '9') {
n = line[offset]; n = line[offset];
} else { } else {
inline for (numbers, 0..) |word, value| { for (words, 0..) |word, value| {
if (std.mem.startsWith(u8, line[offset..], word)) { if (std.mem.startsWith(u8, line[offset..], word)) {
n = value + zero; n = @as(u8, @intCast(value)) + zero;
break; break;
} }
} }
@ -85,8 +57,7 @@ test "silver" {
\\a1b2c3d4e5f \\a1b2c3d4e5f
\\treb7uchet \\treb7uchet
; ;
const sln = try silver(input); try std.testing.expectEqual(@as(u32, 142), try solve(input, &[_][]u8{}));
try std.testing.expectEqual(@as(u32, 142), sln);
} }
test "gold" { test "gold" {
@ -99,6 +70,5 @@ test "gold" {
\\zoneight234 \\zoneight234
\\7pqrstsixteen \\7pqrstsixteen
; ;
const sln = try gold(input); try std.testing.expectEqual(@as(u32, 281), try solve(input, &numbers));
try std.testing.expectEqual(@as(u32, 281), sln);
} }