advent-of-code/2015/day1.zig

55 lines
1.4 KiB
Zig

const std = @import("std");
fn part1(directions: std.ArrayList(u8), floor: *i16) void {
for (directions.items) |direction| {
if (direction == '(') {
floor.* += 1;
} else if (direction == ')') {
floor.* -= 1;
}
}
}
fn part2(directions: std.ArrayList(u8), pos: *i16) void {
var floor: i16 = 0;
for (directions.items) |direction| {
if (direction == '(') {
floor += 1;
} else if (direction == ')') {
floor -= 1;
}
pos.* += 1;
if (floor == -1) break;
}
}
pub fn main() !void {
const file = try std.fs.cwd().openFile("day1.txt", .{});
defer file.close();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();
var buf = std.io.bufferedReader(file.reader());
var directions = std.ArrayList(u8).init(alloc);
defer directions.deinit();
while (true) {
buf.reader().streamUntilDelimiter(directions.writer(), '\n', null) catch |err| switch (err) {
error.EndOfStream => break,
else => return err,
};
}
var floor: i16 = 0;
var position: i16 = 0;
part1(directions, &floor);
part2(directions, &position);
std.debug.print("Ending floor: {d}\n", .{floor});
std.debug.print("Position when first entering basement: {d}\n", .{position});
}