1
0

day11 part2
Some checks failed
Build and test / test (push) Failing after 1m48s

This commit is contained in:
xeals 2023-12-11 18:01:05 +11:00
parent 33297cb653
commit 96a2a09620
Signed by: xeals
SSH Key Fingerprint: SHA256:pRv+8swQDA+/LuZ7NHj9m006BbKexlNK62OUA01ZZBc

View File

@ -44,7 +44,7 @@ fn findGaps(comptime T: type, alloc: mem.Allocator, occupied: std.AutoHashMap(T,
return gaps.toOwnedSlice();
}
fn expand(comptime T: type, alloc: mem.Allocator, galaxies: []Point(T)) !void {
fn expand(comptime T: type, alloc: mem.Allocator, galaxies: []Point(T), scale: T) !void {
var seen_cols = std.AutoHashMap(T, void).init(alloc);
defer seen_cols.deinit();
var seen_rows = std.AutoHashMap(T, void).init(alloc);
@ -60,21 +60,19 @@ fn expand(comptime T: type, alloc: mem.Allocator, galaxies: []Point(T)) !void {
var gap_rows = try findGaps(T, alloc, seen_rows);
defer alloc.free(gap_rows);
std.debug.print("expand x∋{any}, y∋{any}\n", .{ gap_cols, gap_rows });
for (0..galaxies.len) |i| {
const galaxy = galaxies[i];
var col_offset: T = 0;
for (gap_cols) |gap| {
if (gap > galaxy.x) break;
col_offset += 1;
col_offset += scale - 1;
}
var row_offset: T = 0;
for (gap_rows) |gap| {
if (gap > galaxy.y) break;
row_offset += 1;
row_offset += scale - 1;
}
galaxies[i] = Point(T){ .x = galaxy.x + col_offset, .y = galaxy.y + row_offset };
@ -85,7 +83,7 @@ fn absDiff(comptime T: type, a: T, b: T) T {
return @max(a, b) - @min(a, b);
}
fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
fn solvePart(alloc: mem.Allocator, input: []const u8, scale: usize) !usize {
var galaxies = std.ArrayList(Point(usize)).init(alloc);
defer galaxies.deinit();
@ -105,7 +103,7 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
y += 1;
}
try expand(usize, alloc, galaxies.items);
try expand(usize, alloc, galaxies.items, scale);
var distance: usize = 0;
for (galaxies.items, 0..) |a, i| {
@ -115,7 +113,11 @@ fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
}
}
return .{ .a = distance, .b = 0 };
return distance;
}
fn solve(alloc: mem.Allocator, input: []const u8) !Solution {
return .{ .a = try solvePart(alloc, input, 2), .b = try solvePart(alloc, input, 1_000_000) };
}
test "silver" {
@ -131,14 +133,23 @@ test "silver" {
\\.......#..
\\#...#.....
;
const sln = try solve(std.testing.allocator, input);
try std.testing.expectEqual(@as(usize, 374), sln.a);
const sln = try solvePart(std.testing.allocator, input, 2);
try std.testing.expectEqual(@as(usize, 374), sln);
}
test "gold" {
const input =
\\
\\...#......
\\.......#..
\\#.........
\\..........
\\......#...
\\.#........
\\.........#
\\..........
\\.......#..
\\#...#.....
;
const sln = try solve(std.testing.allocator, input);
try std.testing.expectEqual(@as(usize, 0), sln.b);
try std.testing.expectEqual(@as(usize, 1030), try solvePart(std.testing.allocator, input, 10));
try std.testing.expectEqual(@as(usize, 8410), try solvePart(std.testing.allocator, input, 100));
}