solve day 1

This commit is contained in:
Rokas Puzonas 2023-12-02 13:42:48 +02:00
commit 9e556e8bce
4 changed files with 223 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
zig-cache
zig-out

70
build.zig Normal file
View File

@ -0,0 +1,70 @@
const std = @import("std");
// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard optimization options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
const exe = b.addExecutable(.{
.name = "advent-of-code-2023",
// In this case the main source file is merely a path, however, in more
// complicated build scripts, this could be a generated file.
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
// step when running `zig build`).
b.installArtifact(exe);
// This *creates* a Run step in the build graph, to be executed when another
// step is evaluated that depends on it. The next line below will establish
// such a dependency.
const run_cmd = b.addRunArtifact(exe);
// By making the run step depend on the install step, it will be run from the
// installation directory rather than directly from within the cache directory.
// This is not necessary, however, if the application depends on other installed
// files, this ensures they will be present and in the expected location.
run_cmd.step.dependOn(b.getInstallStep());
// This allows the user to pass arguments to the application in the build
// command itself, like this: `zig build run -- arg1 arg2 etc`
if (b.args) |args| {
run_cmd.addArgs(args);
}
// This creates a build step. It will be visible in the `zig build --help` menu,
// and can be selected like this: `zig build run`
// This will evaluate the `run` step rather than the default, which is "install".
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const unit_tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
const run_tests = b.addRunArtifact(unit_tests);
// Similar to creating the run step earlier, this exposes a `test` step to
// the `zig build --help` menu, providing a way for the user to request
// running the unit tests.
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&run_tests.step);
}

116
src/day1.zig Normal file
View File

@ -0,0 +1,116 @@
const std = @import("std");
const StringArray = std.ArrayList([]const u8);
const digits = [_][]const u8{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
pub fn part1(lines: [][]const u8) u32 {
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 sum;
}
pub fn part2(lines: [][]const u8) u32 {
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 sum;
}
test "part 1 example" {
var input = [_][]const u8{
"1abc2",
"pqr3stu8vwx",
"a1b2c3d4e5f",
"treb7uchet",
};
var actual = part1(&input);
var expected: u32 = 142;
try std.testing.expectEqual(expected, actual);
}
test "part 2 example" {
var input = [_][]const u8{
"two1nine",
"eightwothree",
"abcone2threexyz",
"xtwone3four",
"4nineeightseven2",
"zoneight234",
"7pqrstsixteen",
};
var actual = part2(&input);
var expected: u32 = 281;
try std.testing.expectEqual(expected, actual);
}

35
src/main.zig Normal file
View File

@ -0,0 +1,35 @@
const std = @import("std");
const StringArray = std.ArrayList([]const u8);
const Day1 = @import("./day1.zig");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer {
if (gpa.deinit() == .leak) @panic("Leaked memory");
}
var file = try std.fs.cwd().openFile("input.txt", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var reader = buf_reader.reader();
var lines = StringArray.init(allocator);
defer {
for (lines.items) |line| {
allocator.free(line);
}
lines.deinit();
}
var line_buf: [1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&line_buf, '\n')) |line| {
var trimmed_line = std.mem.trimRight(u8, line, &.{'\r'});
try lines.append(try allocator.dupe(u8, trimmed_line));
}
std.debug.print("day1: {d}\n", .{Day1.part1(lines.items)});
std.debug.print("day2: {d}\n", .{Day1.part2(lines.items)});
}