Skip to content

Commit

Permalink
Added day 5 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
3rfaan committed Dec 6, 2024
1 parent c8e4556 commit f7731d4
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/bin/05.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,24 @@ pub fn part_one(input: &str) -> Option<u32> {
}

pub fn part_two(input: &str) -> Option<u32> {
None
let manual = Manual::from(input);
let mut sum = 0;

manual
.updates
.iter()
.filter(|&update| !manual.is_correct_order(update)) // Find incorrect updates
.for_each(|update| {
let sorted_update = manual.sort_incorrect_update(update.clone());

let mid = sorted_update.len() / 2;
sum += sorted_update[mid];
});

Some(sum)
}

#[derive(Clone)]
struct Manual {
rules: Vec<(u32, u32)>,
updates: Vec<Vec<u32>>,
Expand All @@ -42,6 +57,20 @@ impl Manual {
_ => true,
})
}

fn sort_incorrect_update(&self, mut update: Vec<u32>) -> Vec<u32> {
update.sort_by(|&x, &y| {
if self.rules.contains(&(x, y)) {
std::cmp::Ordering::Less
} else if self.rules.contains(&(y, x)) {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
});

update
}
}

impl From<&str> for Manual {
Expand Down

0 comments on commit f7731d4

Please sign in to comment.