Add zig implementation of day 1

This commit is contained in:
Kienan Stewart 2021-12-04 22:08:15 -05:00
parent 034e1907a5
commit fdc4238e8d
3 changed files with 66 additions and 1 deletions

2
.gitignore vendored
View File

@ -1 +1,3 @@
bin/
zig-out/
zig-cache/

27
day1/build.zig Normal file
View File

@ -0,0 +1,27 @@
const std = @import("std");
pub fn build(b: *std.build.Builder) 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 release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("day1", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}

36
day1/src/main.zig Normal file
View File

@ -0,0 +1,36 @@
const std = @import("std");
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = &arena.allocator;
// Read our input
var f = try std.fs.cwd().openFile("input", .{});
defer f.close();
var contents = try f.readToEndAlloc(alloc, std.math.maxInt(u32));
defer alloc.free(contents);
var it = std.mem.tokenize(contents, "\n");
var sum: u64 = 0;
var sum2: u64 = 0;
while (it.next()) |v| {
var val: u64 = try std.fmt.parseInt(u64, v, 10);
val /= 3;
val -= 2;
sum += val;
sum2 += val;
while (val > 0) {
val /= 3;
if (val < 2) {
val = 0;
}
else {
val -= 2;
}
sum2 += val;
}
}
std.log.info("[Part 1] Sum: {}", .{sum});
std.log.info("[Part 2] Sum: {}", .{sum2});
}