Solutions of most (39 out of 50 so far) puzzles in Zig (system language, alternative for C). My first experience with it.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.7 KiB

const std = @import("std");
const Char = enum(u2) {
Galaxy,
Empty,
};
fn solve(projections: [2][]const u32) u32 {
var result: u32 = 0;
for (projections) |projection| {
var i: usize = 0;
while (i < projection.len) : (i += 1) {
if (projection[i] == 0) {
continue;
}
var distance: u32 = 0;
var j = i + 1;
while (j < projection.len) : (j += 1) {
if (projection[j] == 0) {
distance += 2;
} else {
distance += 1;
result += projection[i] * projection[j] * distance;
}
}
}
}
return result;
}
fn charLinesToProjections(allocator: std.mem.Allocator, char_lines: [][]const Char) ![2][]const u32 {
var rows = try allocator.alloc(u32, char_lines.len);
var columns = try allocator.alloc(u32, char_lines[0].len);
@memset(rows, 0);
@memset(columns, 0);
for (char_lines, 0..) |char_line, i| {
for (char_line, 0..) |char, j| {
if (char == .Galaxy) {
rows[i] += 1;
columns[j] += 1;
}
}
}
return .{ rows, columns };
}
fn readInput(allocator: std.mem.Allocator, reader: anytype) ![][]const Char {
var lines = std.ArrayList([]Char).init(allocator);
var line_buffer: [1000]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line_ref| {
var line = try allocator.alloc(Char, line_ref.len);
for (line_ref, line) |raw_char, *char| {
char.* = switch (raw_char) {
'#' => .Galaxy,
'.' => .Empty,
else => unreachable,
};
}
try lines.append(line);
}
return lines.items;
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const raw_in = std.io.getStdIn();
var buffered_reader = std.io.bufferedReader(raw_in.reader());
var reader = buffered_reader.reader();
var allocator_buffer: [1_000_000]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&allocator_buffer);
var allocator = fba.allocator();
var lines_arena = std.heap.ArenaAllocator.init(allocator);
const lines_allocator = lines_arena.allocator();
const char_lines = try readInput(lines_allocator, reader);
var projections_arena = std.heap.ArenaAllocator.init(allocator);
const projections_allocator = projections_arena.allocator();
const projections = try charLinesToProjections(projections_allocator, char_lines);
lines_arena.deinit();
const result = solve(projections);
projections_arena.deinit();
try stdout.print("{d}\n", .{result});
}