This commit is contained in:
parent
ec97bd8ad7
commit
87d3e72276
@ -4,9 +4,12 @@ const util = @import("util.zig");
|
|||||||
pub fn main() !void {
|
pub fn main() !void {
|
||||||
const input = @embedFile("data/day01.txt");
|
const input = @embedFile("data/day01.txt");
|
||||||
const sln = try solve(input);
|
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 {
|
fn solve(input: []const u8) !u32 {
|
||||||
var sum: u32 = 0;
|
var sum: u32 = 0;
|
||||||
|
|
||||||
@ -18,17 +21,27 @@ fn solve(input: []const u8) !u32 {
|
|||||||
|
|
||||||
var first: u8 = 0;
|
var first: u8 = 0;
|
||||||
var last: u8 = 0;
|
var last: u8 = 0;
|
||||||
for (line) |char| {
|
|
||||||
if (char < '0' or char > '9') {
|
for (0..line.len) |offset| {
|
||||||
continue;
|
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) {
|
if (first == 0) {
|
||||||
first = char;
|
first = n;
|
||||||
|
}
|
||||||
|
last = n;
|
||||||
}
|
}
|
||||||
last = char;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const zero = @as(u8, '0');
|
|
||||||
const cal_value = (first - zero) * 10 + (last - zero);
|
const cal_value = (first - zero) * 10 + (last - zero);
|
||||||
sum += cal_value;
|
sum += cal_value;
|
||||||
}
|
}
|
||||||
@ -38,11 +51,14 @@ fn solve(input: []const u8) !u32 {
|
|||||||
|
|
||||||
test "sample" {
|
test "sample" {
|
||||||
const input =
|
const input =
|
||||||
\\1abc2
|
\\two1nine
|
||||||
\\pqr3stu8vwx
|
\\eightwothree
|
||||||
\\a1b2c3d4e5f
|
\\abcone2threexyz
|
||||||
\\treb7uchet
|
\\xtwone3four
|
||||||
|
\\4nineeightseven2
|
||||||
|
\\zoneight234
|
||||||
|
\\7pqrstsixteen
|
||||||
;
|
;
|
||||||
const sln = try solve(input);
|
const sln = try solve(input);
|
||||||
try std.testing.expectEqual(@as(u32, 142), sln);
|
try std.testing.expectEqual(@as(u32, 281), sln);
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user