aoc2015/day3_p1.zig
2024-12-08 00:16:16 +01:00

45 lines
1.2 KiB
Zig

const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
const stdin = std.io.getStdIn();
var buf_io = std.io.bufferedReader(stdin.reader());
var reader = buf_io.reader();
const text = try reader.readAllAlloc(allocator, 100000);
defer allocator.free(text);
std.debug.print("{}", .{try visit(allocator, text)});
}
fn visit(allocator: std.mem.Allocator, seq: []const u8) !u32 {
var visited = std.AutoHashMap([2]i32, void).init(allocator);
defer visited.deinit();
var current: [2]i32 = .{ 0, 0 };
// Set origin as visited
try visited.put(current, {});
for (seq) |c| {
switch (c) {
'>' => current[0] += 1,
'<' => current[0] -= 1,
'^' => current[1] += 1,
'v' => current[1] -= 1,
else => {},
}
try visited.put(current, {});
}
return visited.count();
}
test "day-tests" {
try std.testing.expectEqual(try visit(std.testing.allocator, ">"), 2);
try std.testing.expectEqual(try visit(std.testing.allocator, "^>v<"), 4);
try std.testing.expectEqual(try visit(std.testing.allocator, "^v^v^v^v"), 2);
}