advent-of-code-2021/13/solve.zig

86 lines
2.4 KiB
Zig
Raw Normal View History

2021-12-17 21:25:44 +00:00
const std = @import("std");
const print = std.debug.print;
const Point = [2]u32;
// const Point = struct {
// x: u32,
// y: u32,
// };
pub fn main() !void {
var alloc = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(!alloc.deinit());
var gpa = &alloc.allocator;
const stdin = std.io.getStdIn().reader();
var res: usize = 0;
var res2: u32 = 0;
var points = std.ArrayList(Point).init(gpa);
defer points.deinit();
var tmp: [256]u8 = undefined;
// read points
while (try stdin.readUntilDelimiterOrEof(&tmp, '\n')) |line| {
if (line.len == 0) {
break;
}
var it = std.mem.split(line, ",");
var x = try std.fmt.parseInt(u32, it.next() orelse unreachable, 10);
var y = try std.fmt.parseInt(u32, it.next() orelse unreachable, 10);
try points.append(Point{x, y});
}
// read folds
while (try stdin.readUntilDelimiterOrEof(&tmp, '\n')) |line| {
const idx: u1 = if (line[11] == 'x') 0 else 1;
const place = try std.fmt.parseInt(u32, line[13..], 10);
var remove = std.ArrayList(usize).init(gpa);
defer remove.deinit();
for (points.items) |_, i| {
var point = points.items[i];
if (point[idx] > place) {
point[idx] = place - (point[idx] - place);
points.items[i] = point;
for (points.items) |other, j| {
if (point[0] == other[0] and point[1] == other[1] and i != j) {
try remove.append(i);
}
}
}
}
std.mem.reverse(usize, remove.items);
for (remove.items) |i| {
_ = points.swapRemove(i);
}
if (res == 0) res = points.items.len;
}
print("{}\n", .{res});
var maxX: u32 = 0;
var maxY: u32 = 0;
for (points.items) |point| {
maxX = std.math.max(maxX, point[0]);
maxY = std.math.max(maxY, point[1]);
}
var y: u32 = 0;
while (y <= maxY) : (y += 1) {
var x: u32 = 0;
while (x <= maxX) : (x += 1) {
var char: [1]u8 = [1]u8{'.'};
for (points.items) |point| {
if (point[0] == x and point[1] == y) {
char[0] = '#';
}
}
print("{s}", .{char});
}
print("\n", .{});
}
}