Skip to content

Commit

Permalink
Fix regressions
Browse files Browse the repository at this point in the history
  • Loading branch information
maneatingape committed Jan 2, 2025
1 parent 8991a07 commit 7fc6572
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 20 deletions.
2 changes: 1 addition & 1 deletion src/year2016/day18.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ fn count(input: &str, rows: u32) -> u32 {
// Count the traps in each row.
total += row.count_ones();
// Only consider the left and right values for the next row.
row = (row << 1) ^ (row >> 1) & mask;
row = ((row << 1) ^ (row >> 1)) & mask;
}

// We want the number of safe tiles so convert from the number of traps.
Expand Down
37 changes: 18 additions & 19 deletions src/year2020/day21.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
//! [`Day 16`]: crate::year2020::day16
//! [`count_ones`]: u32::count_ones
use crate::util::hash::*;
use std::collections::BTreeMap;

pub struct Input<'a> {
ingredients: FastMap<&'a str, Ingredient>,
Expand Down Expand Up @@ -102,34 +103,32 @@ pub fn part1(input: &Input<'_>) -> u32 {
}

pub fn part2(input: &Input<'_>) -> String {
let mut ingredients = input.ingredients.clone();
ingredients.retain(|_, v| v.candidates != 0);

let inverse_allergens: FastMap<_, _> =
input.allergens.iter().map(|(k, v)| (1 << v, k)).collect();

// There must be at least one ingredient with only one allergen.
let mut todo: Vec<_> = ingredients
let mut todo: Vec<_> = input
.ingredients
.iter()
.filter(|(_, v)| v.candidates.count_ones() == 1)
.map(|(k, v)| (*k, v.candidates))
.filter_map(|(&k, &v)| (v.candidates != 0).then_some((k, v.candidates)))
.collect();
let mut done = Vec::new();
let mut done = BTreeMap::new();

// Eliminate known allergens from other ingredients.
while let Some(pair @ (next, allergen)) = todo.pop() {
ingredients.remove(next);
done.push(pair);

for (name, ingredient) in &mut ingredients {
ingredient.candidates &= !allergen;
if ingredient.candidates.count_ones() == 1 {
todo.push((name, ingredient.candidates));
while done.len() < todo.len() {
let mut mask = 0;

// There must be at least one ingredient with only one allergen.
for (name, candidates) in &todo {
if candidates.count_ones() == 1 {
let allergen = inverse_allergens[candidates];
done.insert(*allergen, *name);

mask |= candidates;
}
}

todo.iter_mut().for_each(|(_, candidates)| *candidates &= !mask);
}

// Sort by alphabetical order of the allergens.
done.sort_by_cached_key(|(_, v)| inverse_allergens[v]);
done.iter().map(|(k, _)| *k).collect::<Vec<_>>().join(",")
done.into_values().collect::<Vec<_>>().join(",")
}

0 comments on commit 7fc6572

Please sign in to comment.