Skip to main content

aoc/year2025/
day10.rs

1//! # Factory
2use std::array::from_fn;
3
4use crate::util::bitset::*;
5use crate::util::math::*;
6use crate::util::parse::*;
7
8const MAX_BUTTONS: usize = 14;
9const MAX_JOLTAGES: usize = 11;
10
11type Column = [i32; MAX_JOLTAGES];
12
13pub struct Machine {
14    lights: u32,
15    buttons: Vec<u32>,
16    joltages: Vec<i32>,
17}
18
19struct Subspace {
20    rank: usize,
21    nullity: usize,
22    lcm: i32,
23    rhs: Column,
24    basis: Vec<Basis>,
25}
26
27struct Basis {
28    limit: i32,
29    cost: i32,
30    vs: Column,
31}
32
33pub fn parse(input: &str) -> Vec<Machine> {
34    input.lines().map(parse_machine).collect()
35}
36
37pub fn part1(input: &[Machine]) -> u32 {
38    input.iter().map(configure_lights).sum()
39}
40
41pub fn part2(input: &[Machine]) -> i32 {
42    input.iter().map(configure_joltages).sum()
43}
44
45/// Convert light patterns and buttons to bitmasks to speed up part one.
46fn parse_machine(line: &str) -> Machine {
47    let tokens: Vec<_> = line.split_ascii_whitespace().collect();
48    let last = tokens.len() - 1;
49
50    let lights = tokens[0][1..]
51        .bytes()
52        .enumerate()
53        .fold(0, |light, (i, b)| light | (u32::from(b == b'#') << i));
54    let buttons = tokens[1..last]
55        .iter()
56        .map(|token| token.iter_unsigned().fold(0, |button, i: u32| button | (1 << i)))
57        .collect();
58    let joltages = tokens[last].iter_signed().collect();
59
60    Machine { lights, buttons, joltages }
61}
62
63/// Check all patterns with one set bit, then patterns with two set bits, and so on,
64/// returning early as soon as we find a match without checking all possible combinations.
65fn configure_lights(machine: &Machine) -> u32 {
66    let Machine { lights, buttons, joltages } = machine;
67    let width = joltages.len();
68    let height = buttons.len();
69
70    let mut rank = 0;
71    let mut h = [0; MAX_BUTTONS];
72    let mut u: [u32; MAX_BUTTONS] = from_fn(|row| 1 << row);
73
74    h[..height].copy_from_slice(buttons);
75
76    for col in 0..width {
77        let mask = 1 << col;
78        let Some(found) = (rank..height).find(|&row| h[row] & mask != 0) else {
79            continue;
80        };
81
82        h.swap(rank, found);
83        u.swap(rank, found);
84
85        for row in 0..height {
86            if row != rank && h[row] & mask != 0 {
87                h[row] ^= h[rank];
88                u[row] ^= u[rank];
89            }
90        }
91
92        rank += 1;
93    }
94
95    let nullity = height - rank;
96    let particular_solution = (0..rank).fold(0, |particular_solution, row| {
97        let mask = h[row].isolate_lowest_one();
98        particular_solution ^ if lights & mask == 0 { 0 } else { u[row] }
99    });
100
101    (0..1 << nullity)
102        .map(|i| {
103            i.biterator().fold(particular_solution, |presses, j| presses ^ u[rank + j]).count_ones()
104        })
105        .min()
106        .unwrap()
107}
108
109/// Convert the buttons and joltages to simultaneous equations,
110/// then use [Gaussian Elimination](https://en.wikipedia.org/wiki/Gaussian_elimination)
111/// to reduce (the up to 13) dimensions of the full solution space to a (between 0 and 3)
112/// dimensional subspace of only the free variables.
113fn configure_joltages(machine: &Machine) -> i32 {
114    let subspace @ Subspace { rank, nullity, lcm, rhs, .. } = gaussian_elimination(machine);
115    let particular_solution = rhs[..rank].iter().sum();
116
117    if nullity == 0 {
118        particular_solution / lcm
119    } else {
120        let remaining = (1 << subspace.basis.len()) - 1;
121        recurse(&subspace, rhs, remaining, particular_solution).unwrap()
122    }
123}
124
125fn gaussian_elimination(machine: &Machine) -> Subspace {
126    let Machine { buttons, joltages, .. } = machine;
127    let width = buttons.len();
128    let height = joltages.len();
129
130    let mut equations = [[0; MAX_BUTTONS]; MAX_JOLTAGES];
131
132    for row in 0..height {
133        equations[row][width] = joltages[row];
134    }
135
136    for col in 0..width {
137        let mut limit = i32::MAX;
138
139        for row in buttons[col].biterator() {
140            equations[row][col] = 1;
141            limit = limit.min(joltages[row]);
142        }
143
144        equations[height][col] = limit;
145    }
146
147    let mut rank = 0;
148    let mut last = width;
149
150    while rank < height && rank < last {
151        if let Some(found) = (rank..height)
152            .filter(|&row| equations[row][rank] != 0)
153            .min_by_key(|&row| equations[row][rank].abs())
154        {
155            equations.swap(rank, found);
156            let mut pivot = equations[rank][rank];
157
158            if pivot < 0 {
159                pivot *= -1;
160                equations[rank][rank..=width].iter_mut().for_each(|c| *c *= -1);
161            }
162
163            for row in 0..height {
164                let coefficient = equations[row][rank];
165                if row != rank && coefficient != 0 {
166                    for col in 0..equations[row].len() {
167                        equations[row][col] =
168                            pivot * equations[row][col] - coefficient * equations[rank][col];
169                    }
170                }
171            }
172
173            rank += 1;
174        } else {
175            last -= 1;
176            equations[..=height].iter_mut().for_each(|row| row.swap(rank, last));
177        }
178    }
179
180    let lcm = (0..rank).fold(1, |lcm, pivot| lcm.lcm(equations[pivot][pivot]));
181
182    for (pivot, equation) in equations[..rank].iter_mut().enumerate() {
183        let q = lcm / equation[pivot];
184        equation[rank..=width].iter_mut().for_each(|c| *c *= q);
185    }
186
187    let nullity = width - rank;
188    let rhs = from_fn(|row| equations[row][width]);
189    let basis = Vec::from_fn(nullity, |col| {
190        let limit = equations[height][col + rank];
191        let vs = from_fn(|row| equations[row][rank + col]);
192        let cost = lcm - vs[..rank].iter().sum::<i32>();
193        Basis { limit, cost, vs }
194    });
195
196    Subspace { rank, nullity, lcm, rhs, basis }
197}
198
199fn recurse(subspace: &Subspace, mut rhs: Column, remaining: u32, presses: i32) -> Option<i32> {
200    let rank = subspace.rank;
201    let mut temp = rhs;
202
203    for i in remaining.biterator() {
204        let free = &subspace.basis[i];
205        for (row, &v) in free.vs[..rank].iter().enumerate() {
206            if v < 0 {
207                temp[row] -= v * free.limit;
208            }
209        }
210    }
211
212    let mut min_value = i32::MAX;
213    let mut min_index = usize::MAX;
214    let mut global_lower = 0;
215    let mut global_upper = 0;
216
217    for i in remaining.biterator() {
218        let free = &subspace.basis[i];
219        let mut lower = 0;
220        let mut upper = free.limit;
221
222        for (&v, &rhs) in free.vs[..rank].iter().zip(&temp) {
223            if v > 0 {
224                upper = upper.min(rhs / v);
225            }
226            if v < 0 {
227                let rhs = rhs + v * free.limit;
228                lower = lower.max((rhs + v + 1) / v);
229            }
230        }
231
232        let size = upper - lower + 1;
233        if 0 < size && size < min_value {
234            min_value = size;
235            min_index = i;
236            global_lower = lower;
237            global_upper = upper;
238        }
239    }
240
241    if min_index == usize::MAX {
242        return None;
243    }
244
245    let remaining = remaining ^ (1 << min_index);
246    let lower = global_lower;
247    let upper = global_upper;
248    let Basis { cost, vs, .. } = &subspace.basis[min_index];
249    let cost = *cost;
250    let lcm = subspace.lcm;
251
252    if remaining != 0 {
253        rhs[..rank].iter_mut().zip(vs).for_each(|(rhs, v)| *rhs -= (lower - 1) * v);
254
255        (lower..upper + 1)
256            .filter_map(|n| {
257                rhs[..rank].iter_mut().zip(vs).for_each(|(rhs, v)| *rhs -= v);
258                recurse(subspace, rhs, remaining, presses + n * cost)
259            })
260            .min()
261    } else if cost >= 0 {
262        (lower..upper + 1).find_map(|n| {
263            let total = (presses + n * cost) / lcm;
264            rhs[..rank].iter().zip(vs).all(|(rhs, v)| (rhs - n * v) % lcm == 0).then_some(total)
265        })
266    } else {
267        (lower..upper + 1).rev().find_map(|n| {
268            let total = (presses + n * cost) / lcm;
269            rhs[..rank].iter().zip(vs).all(|(rhs, v)| (rhs - n * v) % lcm == 0).then_some(total)
270        })
271    }
272}