118 lines
3.0 KiB
Zig
118 lines
3.0 KiB
Zig
const std = @import("std");
|
|
const aoc = @import("./aoc.zig");
|
|
const Allocator = std.mem.Allocator;
|
|
|
|
const digits = [_][]const u8{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
|
|
|
|
pub fn part1(input: *aoc.Input) !aoc.Result {
|
|
const lines = input.lines;
|
|
|
|
var sum: u32 = 0;
|
|
for (lines) |line| {
|
|
var first_digit: u8 = 0;
|
|
var last_digit: u8 = 0;
|
|
|
|
for (line) |c| {
|
|
if (!std.ascii.isDigit(c)) continue;
|
|
|
|
if (first_digit == 0) {
|
|
first_digit = c - '0';
|
|
last_digit = first_digit;
|
|
} else {
|
|
last_digit = c - '0';
|
|
}
|
|
}
|
|
|
|
var number = 10*first_digit + last_digit;
|
|
sum += number;
|
|
}
|
|
|
|
return .{ .uint = sum };
|
|
}
|
|
|
|
pub fn part2(input: *aoc.Input) !aoc.Result {
|
|
const lines = input.lines;
|
|
|
|
var sum: u32 = 0;
|
|
for (lines) |line| {
|
|
var first_digit: u8 = 0;
|
|
{
|
|
var found_first = false;
|
|
var first_idx: usize = 0;
|
|
for (0.., line) |i, c| {
|
|
if (!std.ascii.isDigit(c)) continue;
|
|
|
|
first_digit = c - '0';
|
|
first_idx = i;
|
|
found_first = true;
|
|
break;
|
|
}
|
|
|
|
for (0.., digits) |i, digit| {
|
|
var occurence_opt = std.mem.indexOf(u8, line, digit);
|
|
if (occurence_opt == null) continue;
|
|
var occurence = occurence_opt.?;
|
|
|
|
if (found_first and occurence > first_idx) continue;
|
|
|
|
first_digit = @intCast(i);
|
|
found_first = true;
|
|
first_idx = occurence;
|
|
}
|
|
}
|
|
|
|
var last_digit: u8 = 0;
|
|
{
|
|
var found_last = false;
|
|
var last_idx: usize = 0;
|
|
for (0.., line) |i, c| {
|
|
if (!std.ascii.isDigit(c)) continue;
|
|
|
|
last_digit = c - '0';
|
|
last_idx = i;
|
|
found_last = true;
|
|
}
|
|
|
|
for (0.., digits) |i, digit| {
|
|
var occurence_opt = std.mem.lastIndexOf(u8, line, digit);
|
|
if (occurence_opt == null) continue;
|
|
var occurence = occurence_opt.?;
|
|
|
|
if (found_last and occurence < last_idx) continue;
|
|
|
|
last_digit = @intCast(i);
|
|
found_last = true;
|
|
last_idx = occurence;
|
|
}
|
|
}
|
|
|
|
var number = 10*first_digit + last_digit;
|
|
sum += number;
|
|
}
|
|
|
|
return .{ .uint = sum };
|
|
}
|
|
|
|
test "part 1 example" {
|
|
var example_input = [_][]const u8{
|
|
"1abc2",
|
|
"pqr3stu8vwx",
|
|
"a1b2c3d4e5f",
|
|
"treb7uchet",
|
|
};
|
|
try aoc.expectAnswerUInt(part1, 142, &example_input);
|
|
}
|
|
|
|
test "part 2 example" {
|
|
var example_input = [_][]const u8{
|
|
"two1nine",
|
|
"eightwothree",
|
|
"abcone2threexyz",
|
|
"xtwone3four",
|
|
"4nineeightseven2",
|
|
"zoneight234",
|
|
"7pqrstsixteen",
|
|
};
|
|
try aoc.expectAnswerUInt(part2, 281, &example_input);
|
|
}
|