Finish day09, part 1

This commit is contained in:
ktkk 2025-12-09 09:17:25 +00:00
parent 862f25d6d8
commit d1e798bdbf
2 changed files with 582 additions and 2 deletions

View file

@ -1,7 +1,91 @@
const std = @import("std");
pub const title = "Day 09";
pub const title = "Day 09: Movie Theater";
pub fn run(_: std.mem.Allocator) !void {
pub fn run(allocator: std.mem.Allocator) !void {
const input = @embedFile("./input/day09.txt");
//const input =
// \\7,1
// \\11,1
// \\11,7
// \\9,7
// \\9,5
// \\2,5
// \\2,3
// \\7,3
// ;
var lines = std.mem.tokenizeScalar(u8, input, '\n');
var tiles: std.ArrayList(Tile) = .empty;
defer tiles.deinit(allocator);
while (lines.next()) |line| {
var coordinates = std.mem.tokenizeScalar(u8, line, ',');
const x = blk: {
const s = coordinates.next() orelse continue;
break :blk try std.fmt.parseUnsigned(u64, s, 10);
};
const y = blk: {
const s = coordinates.next() orelse continue;
break :blk try std.fmt.parseUnsigned(u64, s, 10);
};
try tiles.append(allocator, .{ .x = x, .y = y });
}
var largest_area: usize = 0;
var largest_rectangle: Rectangle = undefined;
for (tiles.items, 0..) |first_tile, i| {
for (tiles.items[i + 1..]) |second_tile| {
const rectangle = first_tile.rectangle(second_tile);
const area = rectangle.area();
if (area > largest_area) {
largest_area = area;
largest_rectangle = rectangle;
}
}
}
std.debug.print("rectangle = {f}\n", .{largest_rectangle});
var buffer: [64]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&buffer);
const stdout = &stdout_writer.interface;
try stdout.print("{d}\n", .{largest_area});
try stdout.flush();
}
const Tile = struct {
x: u64,
y: u64,
const Self = @This();
pub fn format(self: Self, w: *std.io.Writer) std.io.Writer.Error!void {
try w.print("{d},{d}", .{self.x, self.y});
}
pub fn rectangle(self: Self, other_corner: Self) Rectangle {
return .{ .a = self, .b = other_corner };
}
};
const Rectangle = struct {
a: Tile,
b: Tile,
const Self = @This();
pub fn format(self: Self, w: *std.io.Writer) std.io.Writer.Error!void {
try w.print("{f} to {f}", .{self.a, self.b});
}
pub fn area(self: Self) u64 {
const width = @max(self.a.x, self.b.x) - @min(self.a.x, self.b.x) + 1;
const height = @max(self.a.y, self.b.y) - @min(self.a.y, self.b.y) + 1;
return width * height;
}
};