1
0

day01: part2
Some checks failed
Build and test / test (push) Failing after 2m38s

This commit is contained in:
xeals 2023-12-01 16:54:28 +11:00
parent ec97bd8ad7
commit 87d3e72276
Signed by: xeals
SSH Key Fingerprint: SHA256:pRv+8swQDA+/LuZ7NHj9m006BbKexlNK62OUA01ZZBc

View File

@ -4,9 +4,12 @@ const util = @import("util.zig");
pub fn main() !void {
const input = @embedFile("data/day01.txt");
const sln = try solve(input);
std.debug.print("Part 1: {d}", .{sln});
std.debug.print("Solution: {d}", .{sln});
}
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 {
var sum: u32 = 0;
@ -18,17 +21,27 @@ fn solve(input: []const u8) !u32 {
var first: u8 = 0;
var last: u8 = 0;
for (line) |char| {
if (char < '0' or char > '9') {
continue;
for (0..line.len) |offset| {
var n: u8 = 0; // ascii value
if (line[offset] >= '0' and line[offset] <= '9') {
n = line[offset];
} else {
inline for (numbers, 0..) |word, value| {
if (std.mem.startsWith(u8, line[offset..], word)) {
n = value + zero;
break;
}
}
}
if (n != 0) {
if (first == 0) {
first = char;
first = n;
}
last = n;
}
last = char;
}
const zero = @as(u8, '0');
const cal_value = (first - zero) * 10 + (last - zero);
sum += cal_value;
}
@ -38,11 +51,14 @@ fn solve(input: []const u8) !u32 {
test "sample" {
const input =
\\1abc2
\\pqr3stu8vwx
\\a1b2c3d4e5f
\\treb7uchet
\\two1nine
\\eightwothree
\\abcone2threexyz
\\xtwone3four
\\4nineeightseven2
\\zoneight234
\\7pqrstsixteen
;
const sln = try solve(input);
try std.testing.expectEqual(@as(u32, 142), sln);
try std.testing.expectEqual(@as(u32, 281), sln);
}