aoc/year2023/day11.rs
1//! # Cosmic Expansion
2//!
3//! We simplify the problem by treating each axis independently. Consider 4 galaxies on the same
4//! axis at arbitrary non-decreasing values `a b c d`. The pairwise distances are:
5//!
6//! * `b - a`
7//! * `c - b + c - a` => `2c - (a + b)`
8//! * `d - c + d - b + d - a` => `3d - (a + b + c)`
9//!
10//! We can see that each pairwise distance can be expressed as the current coordinate multiplied by
11//! the previous number of galaxies minus the [prefix sum](https://en.wikipedia.org/wiki/Prefix_sum)
12//! of the coordinates of the previous galaxies.
13//!
14//! In the special case that two or more galaxies are at the same coordinate, for example `c == d`:
15//!
16//! * `c - b + c - a` => `2c - (a + b)`
17//! * `d - c + d - b + d - a` => `3d - (a + b + c)` => `2c - (a + b)`
18//! * Total: `2 * [2c - (a + b)]`
19//!
20//! This implies that we only need the *count* of the number of galaxies at each coordinate and
21//! can multiply the total value by that count. This also find gaps with no galaxies to
22//! calculate the expanded coordinates.
23pub struct Input {
24 xs: [usize; 140],
25 ys: [usize; 140],
26}
27
28pub fn parse(input: &str) -> Input {
29 let mut xs = [0; 140];
30 let mut ys = [0; 140];
31
32 for (y, row) in input.lines().enumerate() {
33 for (x, b) in row.bytes().enumerate() {
34 if b == b'#' {
35 xs[x] += 1;
36 ys[y] += 1;
37 }
38 }
39 }
40
41 Input { xs, ys }
42}
43
44pub fn part1(input: &Input) -> usize {
45 axis(&input.xs, 1) + axis(&input.ys, 1)
46}
47
48pub fn part2(input: &Input) -> usize {
49 axis(&input.xs, 999999) + axis(&input.ys, 999999)
50}
51
52fn axis(counts: &[usize], factor: usize) -> usize {
53 let mut gaps = 0;
54 let mut result = 0;
55 let mut prefix_sum = 0;
56 let mut prefix_items = 0;
57
58 for (i, &count) in counts.iter().enumerate() {
59 if count > 0 {
60 let expanded = i + factor * gaps;
61 let extra = prefix_items * expanded - prefix_sum;
62 result += count * extra;
63 prefix_sum += count * expanded;
64 prefix_items += count;
65 } else {
66 gaps += 1;
67 }
68 }
69
70 result
71}