Watch
1
0
Fork
You've already forked advent-of-code
0

2024 Day 1

This commit is contained in:
Jeremy Kaplan 2024-11-30 21:32:08 -08:00
commit c351b2b2c8
6 changed files with 216 additions and 1 deletions

4
2024/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
zig-out
.zig-cache
/input

33
2024/build.zig Normal file
View file

@ -0,0 +1,33 @@
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(.{});
// Creates a step for unit testing. This only builds the test executable
// but does not run it.
const lib_unit_tests = b.addTest(.{
.root_source_file = b.path("src/aoc.zig"),
.target = target,
.optimize = optimize,
});
const run_lib_unit_tests = b.addRunArtifact(lib_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_lib_unit_tests.step);
}

72
2024/build.zig.zon Normal file
View file

@ -0,0 +1,72 @@
.{
// This is the default name used by packages depending on this one. For
// example, when a user runs `zig fetch --save <url>`, this field is used
// as the key in the `dependencies` table. Although the user can choose a
// different name, most users will stick with this provided value.
//
// It is redundant to include "zig" in this name because it is already
// within the Zig package namespace.
.name = "aoc",
// This is a [Semantic Version](https://semver.org/).
// In a future version of Zig it will be used for package deduplication.
.version = "0.0.0",
// This field is optional.
// This is currently advisory only; Zig does not yet do anything
// with this value.
//.minimum_zig_version = "0.11.0",
// This field is optional.
// Each dependency must either provide a `url` and `hash`, or a `path`.
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
// Once all dependencies are fetched, `zig build` no longer requires
// internet connectivity.
.dependencies = .{
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
//.example = .{
// // When updating this field to a new URL, be sure to delete the corresponding
// // `hash`, otherwise you are communicating that you expect to find the old hash at
// // the new URL.
// .url = "https://example.com/foo.tar.gz",
//
// // This is computed from the file contents of the directory of files that is
// // obtained after fetching `url` and applying the inclusion rules given by
// // `paths`.
// //
// // This field is the source of truth; packages do not come from a `url`; they
// // come from a `hash`. `url` is just one of many possible mirrors for how to
// // obtain a package matching this `hash`.
// //
// // Uses the [multihash](https://multiformats.io/multihash/) format.
// .hash = "...",
//
// // When this is provided, the package is found in a directory relative to the
// // build root. In this case the package's hash is irrelevant and therefore not
// // computed. This field and `url` are mutually exclusive.
// .path = "foo",
// // When this is set to `true`, a package is declared to be lazily
// // fetched. This makes the dependency only get fetched if it is
// // actually used.
// .lazy = false,
//},
},
// Specifies the set of files and directories that are included in this package.
// Only files and directories listed here are included in the `hash` that
// is computed for this package. Only files listed here will remain on disk
// when using the zig package manager. As a rule of thumb, one should list
// files required for compilation plus any license(s).
// Paths are relative to the build root. Use the empty string (`""`) to refer to
// the build root itself.
// A directory listed here means that all files within, recursively, are included.
.paths = .{
"build.zig",
"build.zig.zon",
"src",
// For example...
//"LICENSE",
//"README.md",
},
}

30
2024/src/aoc.zig Normal file
View file

@ -0,0 +1,30 @@
const std = @import("std");
pub const Lines = struct {
buf_reader: std.io.BufferedReader(4096, std.fs.File.Reader),
line: std.ArrayList(u8),
pub fn init(allocator: std.mem.Allocator, file: std.fs.File) Lines {
return .{
.buf_reader = std.io.bufferedReader(file.reader()),
.line = std.ArrayList(u8).init(allocator),
};
}
pub fn deinit(self: Lines) void {
self.line.deinit();
}
pub fn next(self: *Lines) !?std.ArrayList(u8) {
const writer = self.line.writer();
const reader = self.buf_reader.reader();
self.line.clearRetainingCapacity();
if (reader.streamUntilDelimiter(writer, '\n', null)) {
return self.line;
} else |err| switch (err) {
error.EndOfStream => return null,
else => return err,
}
}
};

76
2024/src/day01.zig Normal file
View file

@ -0,0 +1,76 @@
const std = @import("std");
const aoc = @import("aoc.zig");
pub fn main() !void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .{};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const file = try std.fs.cwd().openFile("input/day01.txt", .{});
defer file.close();
const stdout_file = std.io.getStdOut().writer();
var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer();
var lines = aoc.Lines.init(allocator, file);
defer lines.deinit();
var left = std.ArrayList(u32).init(allocator);
defer left.deinit();
var right = std.ArrayList(u32).init(allocator);
defer right.deinit();
while (try lines.next()) |line| {
var it = std.mem.tokenizeScalar(u8, line.items, ' ');
const l = it.next().?;
const r = it.next().?;
try left.append(try std.fmt.parseInt(u32, l, 10));
try right.append(try std.fmt.parseInt(u32, r, 10));
}
std.mem.sort(u32, left.items, {}, comptime std.sort.asc(u32));
std.mem.sort(u32, right.items, {}, comptime std.sort.asc(u32));
try stdout.print("{d}\n", .{part1(left, right)});
try stdout.print("{d}\n", .{try part2(allocator, left, right)});
try bw.flush();
}
fn part1(left: std.ArrayList(u32), right: std.ArrayList(u32)) u32 {
var i: usize = 0;
var distance: u32 = 0;
while (i < left.items.len) {
distance += abs_diff(left.items[i], right.items[i]);
i += 1;
}
return distance;
}
fn abs_diff(a: u32, b: u32) u32 {
if (a > b) {
return a - b;
} else {
return b - a;
}
}
fn part2(allocator: std.mem.Allocator, left: std.ArrayList(u32), right: std.ArrayList(u32)) !u32 {
var counts = std.AutoHashMap(u32, u32).init(allocator);
defer counts.deinit();
for (right.items) |r| {
const v = counts.get(r) orelse 0;
try counts.put(r, v + 1);
}
var similarity: u32 = 0;
for (left.items) |l| {
similarity += l * (counts.get(l) orelse 0);
}
return similarity;
}