1use 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
45fn 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
63fn 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
109fn 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 = (0..nullity)
190 .map(|col| {
191 let limit = equations[height][col + rank];
192 let vs = from_fn(|row| equations[row][rank + col]);
193 let cost = lcm - vs[..rank].iter().sum::<i32>();
194 Basis { limit, cost, vs }
195 })
196 .collect();
197
198 Subspace { rank, nullity, lcm, rhs, basis }
199}
200
201fn recurse(subspace: &Subspace, mut rhs: Column, remaining: u32, presses: i32) -> Option<i32> {
202 let rank = subspace.rank;
203 let mut temp = rhs;
204
205 for i in remaining.biterator() {
206 let free = &subspace.basis[i];
207 for (row, &v) in free.vs[..rank].iter().enumerate() {
208 if v < 0 {
209 temp[row] -= v * free.limit;
210 }
211 }
212 }
213
214 let mut min_value = i32::MAX;
215 let mut min_index = usize::MAX;
216 let mut global_lower = 0;
217 let mut global_upper = 0;
218
219 for i in remaining.biterator() {
220 let free = &subspace.basis[i];
221 let mut lower = 0;
222 let mut upper = free.limit;
223
224 for (&v, &rhs) in free.vs[..rank].iter().zip(&temp) {
225 if v > 0 {
226 upper = upper.min(rhs / v);
227 }
228 if v < 0 {
229 let rhs = rhs + v * free.limit;
230 lower = lower.max((rhs + v + 1) / v);
231 }
232 }
233
234 let size = upper - lower + 1;
235 if size > 0 && size < min_value {
236 min_value = size;
237 min_index = i;
238 global_lower = lower;
239 global_upper = upper;
240 }
241 }
242
243 if min_index == usize::MAX {
244 return None;
245 }
246
247 let remaining = remaining ^ (1 << min_index);
248 let lower = global_lower;
249 let upper = global_upper;
250 let Basis { cost, vs, .. } = &subspace.basis[min_index];
251 let cost = *cost;
252 let lcm = subspace.lcm;
253
254 if remaining != 0 {
255 rhs[..rank].iter_mut().zip(vs).for_each(|(rhs, v)| *rhs -= (lower - 1) * v);
256
257 (lower..upper + 1)
258 .filter_map(|n| {
259 rhs[..rank].iter_mut().zip(vs).for_each(|(rhs, v)| *rhs -= v);
260 recurse(subspace, rhs, remaining, presses + n * cost)
261 })
262 .min()
263 } else if cost >= 0 {
264 (lower..upper + 1).find_map(|n| {
265 let total = (presses + n * cost) / lcm;
266 rhs[..rank].iter().zip(vs).all(|(rhs, v)| (rhs - n * v) % lcm == 0).then_some(total)
267 })
268 } else {
269 (lower..upper + 1).rev().find_map(|n| {
270 let total = (presses + n * cost) / lcm;
271 rhs[..rank].iter().zip(vs).all(|(rhs, v)| (rhs - n * v) % lcm == 0).then_some(total)
272 })
273 }
274}