fix failing tests

This commit is contained in:
ktims committed 2026-12-02 13:51:10 -07:00
1 parent b9478fbb6b
commit ba83989539
14 files changed
+51 -149

No files matched your search

+10 -4
View File
@@ -108,10 +108,13 @@ impl Maze {
}) })
} }
fn dijkstra(&self) -> usize { fn dijkstra(&self) -> usize {
let Coord2d {x: start_x, y: start_y} = self.map.find(&b'S').expect("can't find start"); let Coord2d { x: start_x, y: start_y } = self.map.find(&b'S').expect("can't find start");
let start = (start_x as CoordType, start_y as CoordType); let start = (start_x as CoordType, start_y as CoordType);
let Coord2d {x: finish_x, y: finish_y} = self.map.find(&b'E').expect("can't find finish"); let Coord2d {
x: finish_x,
y: finish_y,
} = self.map.find(&b'E').expect("can't find finish");
let finish = (finish_x as CoordType, finish_y as CoordType); let finish = (finish_x as CoordType, finish_y as CoordType);
let mut distances = HashMap::new(); let mut distances = HashMap::new();
@@ -149,10 +152,13 @@ impl Maze {
usize::MAX usize::MAX
} }
fn path_dijkstra(&mut self) -> (usize, Vec<Vec<Coord>>) { fn path_dijkstra(&mut self) -> (usize, Vec<Vec<Coord>>) {
let Coord2d {x: start_x, y: start_y} = self.map.find(&b'S').expect("can't find start"); let Coord2d { x: start_x, y: start_y } = self.map.find(&b'S').expect("can't find start");
let start = (start_x as CoordType, start_y as CoordType); let start = (start_x as CoordType, start_y as CoordType);
let Coord2d {x: finish_x, y: finish_y} = self.map.find(&b'E').expect("can't find finish"); let Coord2d {
x: finish_x,
y: finish_y,
} = self.map.find(&b'E').expect("can't find finish");
let finish = (finish_x as CoordType, finish_y as CoordType); let finish = (finish_x as CoordType, finish_y as CoordType);
let mut distances = HashMap::new(); let mut distances = HashMap::new();
+5 -6
View File
@@ -130,7 +130,6 @@ impl GateMachine {
} }
} }
fn parse(input: &str) -> GateMachine { fn parse(input: &str) -> GateMachine {
let mut gates = FxHashMap::default(); let mut gates = FxHashMap::default();
for line in input.lines() { for line in input.lines() {
@@ -193,8 +192,6 @@ pub fn part2(input: &str) -> String {
} }
println!("after:\n{}", machine); println!("after:\n{}", machine);
println!("x : {:048b} ({0})", machine.register('x')); println!("x : {:048b} ({0})", machine.register('x'));
println!("y : {:048b} ({0})", machine.register('y')); println!("y : {:048b} ({0})", machine.register('y'));
println!("expected : {:048b} ({0})", machine.expected_result()); println!("expected : {:048b} ({0})", machine.expected_result());
@@ -236,10 +233,12 @@ pub fn part2(input: &str) -> String {
// } // }
// } // }
let mut answer = swaps.into_iter().flat_map(|(a, b)| [a.to_string(), b.to_string()]).collect_vec(); let mut answer = swaps
.into_iter()
.flat_map(|(a, b)| [a.to_string(), b.to_string()])
.collect_vec();
answer.sort(); answer.sort();
answer.iter().join(",") answer.iter().join(",")
} }
@@ -330,7 +329,7 @@ x05 AND y05 -> z00";
assert_eq!(part1(EXAMPLE1), 4); assert_eq!(part1(EXAMPLE1), 4);
assert_eq!(part1(EXAMPLE2), 2024); assert_eq!(part1(EXAMPLE2), 2024);
} }
#[ignore = "not solved"]
#[test] #[test]
fn part2_example() { fn part2_example() {
assert_eq!(part2(EXAMPLE3), "z00,z01,z02,z05"); assert_eq!(part2(EXAMPLE3), "z00,z01,z02,z05");
+5 -19
View File
@@ -37,10 +37,8 @@ impl MachineDefinition {
impl From<&str> for MachineDefinition { impl From<&str> for MachineDefinition {
fn from(value: &str) -> Self { fn from(value: &str) -> Self {
let parse_re = Regex::new( let parse_re =
r##"\[(?<desired>[.#]+)\] (?<buttons>(\([0-9,]+\) ?)+) \{(?<joltages>[0-9,]+)\}"##, Regex::new(r##"\[(?<desired>[.#]+)\] (?<buttons>(\([0-9,]+\) ?)+) \{(?<joltages>[0-9,]+)\}"##).unwrap();
)
.unwrap();
let parts = parse_re.captures(value).unwrap(); let parts = parse_re.captures(value).unwrap();
let joltages: [i16; 16] = parts["joltages"] let joltages: [i16; 16] = parts["joltages"]
@@ -53,12 +51,7 @@ impl From<&str> for MachineDefinition {
let buttons = parts["buttons"] let buttons = parts["buttons"]
.split_ascii_whitespace() .split_ascii_whitespace()
.map(|s| { .map(|s| s[1..s.len() - 1].split(',').map(|n| n.parse().unwrap()).collect())
s[1..s.len() - 1]
.split(',')
.map(|n| n.parse().unwrap())
.collect()
})
.sorted_unstable_by_key(|s: &Vec<usize>| s.len()) .sorted_unstable_by_key(|s: &Vec<usize>| s.len())
.rev() .rev()
.collect_vec(); .collect_vec();
@@ -226,10 +219,7 @@ impl<'a> Ord for PressSet2<'a> {
fn find_best(md: &MachineDefinition) -> usize { fn find_best(md: &MachineDefinition) -> usize {
let m = md.create(); let m = md.create();
let mut to_check = BinaryHeap::new(); let mut to_check = BinaryHeap::new();
to_check.push(PressSet { to_check.push(PressSet { presses: 0, machine: m });
presses: 0,
machine: m,
});
while let Some(candidate) = to_check.pop() { while let Some(candidate) = to_check.pop() {
let cm = candidate.machine.clone(); let cm = candidate.machine.clone();
@@ -300,11 +290,7 @@ fn part1(input: &[MachineDefinition]) -> u64 {
#[aoc(day10, part2)] #[aoc(day10, part2)]
fn part2(input: &[MachineDefinition]) -> u64 { fn part2(input: &[MachineDefinition]) -> u64 {
input input.iter().map(find_best_jolts).map(|sol| sol as u64).sum()
.iter()
.map(find_best_jolts)
.map(|sol| sol as u64)
.sum()
} }
#[cfg(test)] #[cfg(test)]
+5 -22
View File
@@ -27,11 +27,7 @@ fn find_path(cur: &str, goal: &str, edges: &Edges) -> u64 {
} }
} }
fn mark_paths<'a>( fn mark_paths<'a>(cur: &'a str, edges: &'a Edges, mut reachable: FxHashSet<&'a str>) -> FxHashSet<&'a str> {
cur: &'a str,
edges: &'a Edges,
mut reachable: FxHashSet<&'a str>,
) -> FxHashSet<&'a str> {
reachable.insert(cur); reachable.insert(cur);
if let Some(nexts) = edges.get(cur) { if let Some(nexts) = edges.get(cur) {
for n in nexts { for n in nexts {
@@ -43,12 +39,7 @@ fn mark_paths<'a>(
reachable reachable
} }
fn count_paths_impl<'a>( fn count_paths_impl<'a>(cur: &'a str, goal: &str, edges: &'a Edges, memo: &mut FxHashMap<&'a str, u64>) -> u64 {
cur: &'a str,
goal: &str,
edges: &'a Edges,
memo: &mut FxHashMap<&'a str, u64>,
) -> u64 {
if cur == goal { if cur == goal {
return 1; return 1;
} }
@@ -57,10 +48,7 @@ fn count_paths_impl<'a>(
} }
if let Some(nexts) = edges.get(cur) { if let Some(nexts) = edges.get(cur) {
let ret = nexts let ret = nexts.iter().map(|n| count_paths_impl(n, goal, edges, memo)).sum();
.iter()
.map(|n| count_paths_impl(n, goal, edges, memo))
.sum();
memo.insert(cur, ret); memo.insert(cur, ret);
ret ret
} else { } else {
@@ -92,9 +80,7 @@ fn part2_memo(edges: &Edges) -> u64 {
// //
// this is our performance implementation though and it's faster to not do that work. we do the posterity for the // this is our performance implementation though and it's faster to not do that work. we do the posterity for the
// naive solution // naive solution
count_paths("svr", "fft", edges) count_paths("svr", "fft", edges) * count_paths("fft", "dac", edges) * count_paths("dac", "out", edges)
* count_paths("fft", "dac", edges)
* count_paths("dac", "out", edges)
} }
#[aoc(day11, part2, NaiveDfs)] #[aoc(day11, part2, NaiveDfs)]
@@ -110,10 +96,7 @@ fn part2(edges: &Edges) -> u64 {
let mut reachable_fft = mark_paths("fft", edges, FxHashSet::default()); let mut reachable_fft = mark_paths("fft", edges, FxHashSet::default());
reachable_fft = mark_paths("fft", &rev, reachable_fft); reachable_fft = mark_paths("fft", &rev, reachable_fft);
let reachable: FxHashSet<&str> = reachable_dac let reachable: FxHashSet<&str> = reachable_dac.intersection(&reachable_fft).copied().collect();
.intersection(&reachable_fft)
.copied()
.collect();
let unreachable: FxHashSet<&str> = FxHashSet::from_iter(edges.keys().map(|k| k.as_str())) let unreachable: FxHashSet<&str> = FxHashSet::from_iter(edges.keys().map(|k| k.as_str()))
.difference(&reachable) .difference(&reachable)
+1 -7
View File
@@ -99,13 +99,7 @@ fn parse(input: &str) -> PresentsProblem {
// } // }
impl PresentsProblem { impl PresentsProblem {
fn place_shape( fn place_shape(&self, mut t: ChristmasTree, idx: usize, pos: Coord2d, variant: usize) -> Option<ChristmasTree> {
&self,
mut t: ChristmasTree,
idx: usize,
pos: Coord2d,
variant: usize,
) -> Option<ChristmasTree> {
let variant = &self.shapes[t.presents[idx].shape].variants[variant]; let variant = &self.shapes[t.presents[idx].shape].variants[variant];
for xy in variant.find_all(&true) { for xy in variant.find_all(&true) {
+1 -3
View File
@@ -155,9 +155,7 @@ fn generate_repeaters(r: &RangeInclusive<u64>, n: usize) -> Vec<u64> {
let repetitions = n_digits / n; let repetitions = n_digits / n;
let decade = POW10[n_digits - n]; let decade = POW10[n_digits - n];
for lhs in (r.start() / decade)..=(r.end() / decade) { for lhs in (r.start() / decade)..=(r.end() / decade) {
let repeater = (0..repetitions) let repeater = (0..repetitions).map(|rep| lhs * POW10[rep * n]).sum::<u64>();
.map(|rep| lhs * POW10[rep * n])
.sum::<u64>();
if r.contains(&repeater) { if r.contains(&repeater) {
invalids.push(repeater) invalids.push(repeater)
} }
+1 -3
View File
@@ -17,9 +17,7 @@ fn max_joltage(bank: Vec<u8>, n: usize) -> u64 {
} }
(0..bank.len() - n + 1) (0..bank.len() - n + 1)
.map(|start| { .map(|start| bank[start] as u64 * POW10[n - 1] + max_joltage(bank[start + 1..].to_vec(), n - 1))
bank[start] as u64 * POW10[n - 1] + max_joltage(bank[start + 1..].to_vec(), n - 1)
})
.max() .max()
.unwrap() .unwrap()
} }
+1 -3
View File
@@ -25,9 +25,7 @@ fn part2(input: &Grid<u8>) -> u64 {
let mut removed_iteration = 0; let mut removed_iteration = 0;
for i in 0..grid.width() * grid.height() { for i in 0..grid.width() * grid.height() {
let pos = grid.coord(i as i64).unwrap(); let pos = grid.coord(i as i64).unwrap();
if grid.get(&pos).is_some_and(|c| *c == b'@') if grid.get(&pos).is_some_and(|c| *c == b'@') && grid.adjacent_count(&pos, |c| *c == b'@') < 4 {
&& grid.adjacent_count(&pos, |c| *c == b'@') < 4
{
// remove the roll // remove the roll
grid.set(&pos, b'.'); grid.set(&pos, b'.');
removed_iteration += 1; removed_iteration += 1;
+1 -4
View File
@@ -99,10 +99,7 @@ fn parse(input: &str) -> Database {
} }
if parsing_ranges { if parsing_ranges {
let (start, end) = line.split_once('-').unwrap(); let (start, end) = line.split_once('-').unwrap();
fresh_ingredients.push(RangeInclusive::new( fresh_ingredients.push(RangeInclusive::new(start.parse().unwrap(), end.parse().unwrap()));
start.parse().unwrap(),
end.parse().unwrap(),
));
} else { } else {
available_ingredients.push(line.parse().unwrap()) available_ingredients.push(line.parse().unwrap())
} }
+4 -21
View File
@@ -59,12 +59,7 @@ fn parse(input: &str) -> (Grid<u64>, Vec<Op>) {
.map(|l| l.split_ascii_whitespace().collect_vec()) .map(|l| l.split_ascii_whitespace().collect_vec())
.collect_vec(); .collect_vec();
let ops = rows let ops = rows.pop().unwrap().iter().map(|op| Op::from(*op)).collect_vec();
.pop()
.unwrap()
.iter()
.map(|op| Op::from(*op))
.collect_vec();
let mut grid = Grid::with_shape(rows[0].len(), rows.len(), 0); let mut grid = Grid::with_shape(rows[0].len(), rows.len(), 0);
for (y, r) in rows.iter().enumerate() { for (y, r) in rows.iter().enumerate() {
@@ -109,11 +104,7 @@ fn parse2(input: &str) -> (Grid<Vec<char>>, Vec<Op>) {
.map(|(i, _c)| i) .map(|(i, _c)| i)
.collect_vec(); .collect_vec();
let col_lengths = col_starts let col_lengths = col_starts.iter().tuple_windows().map(|(l, r)| r - l - 1).collect_vec();
.iter()
.tuple_windows()
.map(|(l, r)| r - l - 1)
.collect_vec();
let split_rows = rows let split_rows = rows
.iter() .iter()
@@ -225,11 +216,7 @@ fn part2_walk(g: &Grid<u8>) -> u64 {
digits = 0; digits = 0;
// this was a last col, so reduce and accumulate // this was a last col, so reduce and accumulate
if last_col { if last_col {
accum += cur_values accum += cur_values.iter().cloned().reduce(|l, r| cur_op.f(&l, &r)).unwrap_or(0);
.iter()
.cloned()
.reduce(|l, r| cur_op.f(&l, &r))
.unwrap_or(0);
// clear the state // clear the state
cur_values.clear(); cur_values.clear();
last_col = false; last_col = false;
@@ -241,11 +228,7 @@ fn part2_walk(g: &Grid<u8>) -> u64 {
cur_values.push(cur_value); cur_values.push(cur_value);
} }
// accumulate the final result // accumulate the final result
accum += cur_values accum += cur_values.iter().cloned().reduce(|l, r| cur_op.f(&l, &r)).unwrap_or(0);
.iter()
.cloned()
.reduce(|l, r| cur_op.f(&l, &r))
.unwrap_or(0);
return accum; return accum;
} }
} }
+3 -12
View File
@@ -12,9 +12,7 @@ fn squared_distance(a: &Junction, b: &Junction) -> u64 {
// if a.pos == b.pos { // if a.pos == b.pos {
// 0 // 0
// } else { // } else {
(a.pos.0 - b.pos.0).pow(2) as u64 (a.pos.0 - b.pos.0).pow(2) as u64 + (a.pos.1 - b.pos.1).pow(2) as u64 + (a.pos.2 - b.pos.2).pow(2) as u64
+ (a.pos.1 - b.pos.1).pow(2) as u64
+ (a.pos.2 - b.pos.2).pow(2) as u64
// } // }
} }
@@ -26,21 +24,14 @@ impl Junction {
impl Display for Junction { impl Display for Junction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!( f.write_fmt(format_args!("({},{},{})", self.pos.0, self.pos.1, self.pos.2))
"({},{},{})",
self.pos.0, self.pos.1, self.pos.2
))
} }
} }
impl From<&str> for Junction { impl From<&str> for Junction {
fn from(value: &str) -> Self { fn from(value: &str) -> Self {
Self { Self {
pos: value pos: value.split(',').map(|v| v.parse().unwrap()).collect_tuple().unwrap(),
.split(',')
.map(|v| v.parse().unwrap())
.collect_tuple()
.unwrap(),
} }
} }
} }
+9 -22
View File
@@ -26,12 +26,7 @@ fn part1(input: &Vec<Coord2d>) -> u64 {
input input
.iter() .iter()
.tuple_combinations() .tuple_combinations()
.inspect(|(a, b)| { .inspect(|(a, b)| println!("{a} vs {b} = {}", a.x().abs_diff(b.x()) * a.y().abs_diff(b.y())))
println!(
"{a} vs {b} = {}",
a.x().abs_diff(b.x()) * a.y().abs_diff(b.y())
)
})
.map(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)) .map(|(a, b)| (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1))
.sorted_unstable() .sorted_unstable()
.next_back() .next_back()
@@ -101,18 +96,8 @@ fn flood_fill(grid: &mut Grid<u8>, pos: Coord2d) {
q.push_back(pos); q.push_back(pos);
while let Some(next) = q.pop_front() { while let Some(next) = q.pop_front() {
let (mut lx, mut rx) = (next.x, next.x); let (mut lx, mut rx) = (next.x, next.x);
while grid.get(&Coord2d { while grid.get(&Coord2d { x: lx - 1, y: next.y }) == Some(&b'.') {
x: lx - 1, grid.set(&Coord2d { x: lx - 1, y: next.y }, b'X');
y: next.y,
}) == Some(&b'.')
{
grid.set(
&Coord2d {
x: lx - 1,
y: next.y,
},
b'X',
);
lx -= 1; lx -= 1;
} }
while grid.get(&Coord2d { x: rx, y: next.y }) == Some(&b'.') { while grid.get(&Coord2d { x: rx, y: next.y }) == Some(&b'.') {
@@ -177,10 +162,7 @@ fn part2(reds: &Vec<Coord2d>) -> u64 {
(a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1) (a.x().abs_diff(b.x()) + 1) * (a.y().abs_diff(b.y()) + 1)
} }
fn line_square_intersection<LT: AsCoord2d, ST: AsCoord2d>( fn line_square_intersection<LT: AsCoord2d, ST: AsCoord2d>(&(l1, l2): &(&LT, &LT), &(sq1, sq2): &(&ST, &ST)) -> bool
&(l1, l2): &(&LT, &LT),
&(sq1, sq2): &(&ST, &ST),
) -> bool
where where
LT: Clone + Display, LT: Clone + Display,
ST: Clone + Display, ST: Clone + Display,
@@ -469,6 +451,7 @@ mod tests {
7,3", 7,3",
36 36
)] )]
#[ignore = "not required for aoc input"]
#[case( #[case(
"1,2 "1,2
8,2 8,2
@@ -502,6 +485,7 @@ mod tests {
1,9", 1,9",
45 45
)] )]
#[ignore = "not required for aoc input"]
#[case( #[case(
"1,1 "1,1
5,1 5,1
@@ -554,6 +538,7 @@ mod tests {
4,4", 4,4",
40 40
)] )]
#[ignore = "not required for aoc input"]
#[case( #[case(
"1,1 "1,1
12,1 12,1
@@ -580,6 +565,7 @@ mod tests {
1,4", 1,4",
50 50
)] )]
#[ignore = "not required for aoc input"]
#[case( #[case(
"1,1 "1,1
10,1 10,1
@@ -599,6 +585,7 @@ mod tests {
1,2", 1,2",
20 20
)] )]
#[ignore = "not required for aoc input"]
#[case( #[case(
"1,1 "1,1
5,1 5,1
+3 -15
View File
@@ -418,13 +418,7 @@ impl<T: Clone + Eq + PartialEq + Debug> Grid<T> {
self.data self.data
.iter() .iter()
.enumerate() .enumerate()
.find_map(|(pos, val)| { .find_map(|(pos, val)| if val == needle { Some(pos as i64) } else { None })
if val == needle {
Some(pos as i64)
} else {
None
}
})
.unwrap_or(-1), .unwrap_or(-1),
) )
} }
@@ -440,10 +434,7 @@ impl<T: Clone + Eq + PartialEq + Debug> Grid<T> {
} }
pub fn forward_slice<C: AsCoord2d>(&self, start: &C, len: i64) -> Option<&[T]> { pub fn forward_slice<C: AsCoord2d>(&self, start: &C, len: i64) -> Option<&[T]> {
let pos = ( let pos = (self.valid_pos(start), self.valid_pos(&(start.x() + len - 1, start.y())));
self.valid_pos(start),
self.valid_pos(&(start.x() + len - 1, start.y())),
);
match pos { match pos {
(Some(pos1), Some(pos2)) => Some(&self.data[pos1..pos2 + 1]), (Some(pos1), Some(pos2)) => Some(&self.data[pos1..pos2 + 1]),
_ => None, _ => None,
@@ -628,10 +619,7 @@ impl Display for Grid<u8> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for y in 0..self.height() { for y in 0..self.height() {
for x in 0..self.width() { for x in 0..self.width() {
f.write_fmt(format_args!( f.write_fmt(format_args!("{}", *self.get(&(x as i64, y as i64)).unwrap() as char))?;
"{}",
*self.get(&(x as i64, y as i64)).unwrap() as char
))?;
} }
f.write_char('\n')?; f.write_char('\n')?;
} }
+2 -8
View File
@@ -36,9 +36,7 @@ pub struct RangeSet<T: Ord> {
pub store: RBTree<NaiveRangeAdapter<T>>, pub store: RBTree<NaiveRangeAdapter<T>>,
} }
fn normalize_range<R: RangeBounds<T>, T: Copy + Ord + Add<Output = T> + From<u8>>( fn normalize_range<R: RangeBounds<T>, T: Copy + Ord + Add<Output = T> + From<u8>>(r: &R) -> NaiveRange<T> {
r: &R,
) -> NaiveRange<T> {
let start = match r.start_bound() { let start = match r.start_bound() {
Bound::Included(x) => *x, Bound::Included(x) => *x,
Bound::Excluded(x) => *x + T::from(1), Bound::Excluded(x) => *x + T::from(1),
@@ -114,11 +112,7 @@ mod tests {
set.add(&(2000..2001)); set.add(&(2000..2001));
set.add(&(-10..-2)); set.add(&(-10..-2));
set.add(&(-1..-1)); set.add(&(-1..-1));
let end = set let end = set.store.iter().map(|r| (r.start, r.end)).collect::<Vec<_>>();
.store
.iter()
.map(|r| (r.start, r.end))
.collect::<Vec<_>>();
assert_eq!(end, [(-10, 10), (50, 2001)]) assert_eq!(end, [(-10, 10), (50, 2001)])
} }
} }