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.

140 lines
3.3 KiB

const std = @import("std");
fn StackList(comptime T: type, comptime capacity_type: type, comptime capacity: capacity_type) type {
return struct {
const Self = @This();
mem: [capacity]T,
length: capacity_type,
fn add(self: *Self, value: T) void {
self.mem[self.length] = value;
self.length += 1;
}
fn has(self: *Self, needle: T) bool {
for (0..self.length) |i| {
if (self.mem[i] == needle) {
return true;
}
}
return false;
}
fn getMutableSlice(self: *Self) []T {
return (&self.mem)[0..self.length];
}
fn getSlice(self: *const Self) []const T {
return self.mem[0..self.length];
}
fn init() Self {
return Self{
.mem = undefined,
.length = 0,
};
}
};
}
fn isMirroredHorizontallyAt(lines: []const []const u8, mirror_before: usize) bool {
var a = mirror_before - 1;
var b = mirror_before;
while (a >= 0 and b < lines.len) {
for (lines[a], lines[b]) |char_a, char_b| {
if (char_a != char_b) {
return false;
}
}
if (a == 0) {
break;
}
a -= 1;
b += 1;
}
return true;
}
fn isMirroredVerticallyAt(lines: []const []const u8, mirror_before: usize) bool {
for (lines) |line| {
var a = mirror_before - 1;
var b = mirror_before;
while (a >= 0 and b < line.len) {
if (line[a] != line[b]) {
return false;
}
if (a == 0) {
break;
}
a -= 1;
b += 1;
}
}
return true;
}
fn solveLines(lines: []const []const u8) usize {
var result: usize = 0;
var column: usize = 1;
while (column < lines[0].len) : (column += 1) {
if (isMirroredVerticallyAt(lines, column)) {
result += column;
}
}
var row: usize = 1;
while (row < lines.len) : (row += 1) {
if (isMirroredHorizontallyAt(lines, row)) {
result += 100 * row;
}
}
return result;
}
pub fn solveAll(reader: anytype) !usize {
var result: usize = 0;
while (true) {
var allocator_buffer: [10000]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&allocator_buffer);
var allocator = fba.allocator();
var lines = StackList([]const u8, usize, 100).init();
var empty_line_reached = false;
var line_buffer: [1000]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| {
if (line.len == 0) {
empty_line_reached = true;
break;
}
lines.add(try allocator.dupe(u8, line));
}
result += solveLines(lines.getSlice());
if (!empty_line_reached) {
return result;
}
}
}
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();
const result = try solveAll(&reader);
try stdout.print("{d}\n", .{result});
}