Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

Commit 50c33f6

Browse files
committed
Clean up day 05 some more
1 parent a909350 commit 50c33f6

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

src/bin/day05/main.rs

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use std::collections::{HashMap, HashSet};
22

33
const ACTUAL_INPUT: &str = include_str!("../../../actual_inputs/2024/05/input.txt");
44

5-
#[derive(Clone)]
65
struct Graph {
76
children: HashMap<usize, HashSet<usize>>,
87
}
@@ -57,13 +56,12 @@ fn is_valid_ordering(rules: &Graph, update: &[usize]) -> bool {
5756
let mut seen = HashSet::new();
5857

5958
let found_violated_order = update.iter().any(|page| {
60-
if let Some(children) = rules.children.get(page) {
61-
if children.iter().any(|child_page| seen.contains(child_page)) {
62-
return true;
63-
}
64-
}
6559
seen.insert(page);
66-
false
60+
rules
61+
.children
62+
.get(page)
63+
.map(|children| children.iter().any(|child_page| seen.contains(child_page)))
64+
.unwrap_or(false)
6765
});
6866

6967
!found_violated_order
@@ -84,25 +82,26 @@ fn p1(input: &str) -> String {
8482
.to_string()
8583
}
8684

87-
fn fix_page_orderings(rules: &Graph, update: &[usize]) -> Vec<usize> {
85+
fn fix_page_ordering(rules: &Graph, update: &[usize]) -> Vec<usize> {
8886
let mut result = update.to_vec();
8987

9088
let empty_hashset = HashSet::new();
9189

9290
for i in 0..result.len() {
9391
let children = rules.children.get(&result[i]).unwrap_or(&empty_hashset);
9492

95-
if let Some(violate_idx) = (0..i)
96-
.rev()
97-
.fold(None, |smallest_violate_idx_so_far, subidx| {
98-
if children.contains(&result[subidx]) {
99-
Some(subidx)
100-
} else {
101-
smallest_violate_idx_so_far
102-
}
103-
})
93+
if let Some(smallest_violate_idx) =
94+
(0..i)
95+
.rev()
96+
.fold(None, |smallest_violate_idx_so_far, inspect_idx| {
97+
if children.contains(&result[inspect_idx]) {
98+
Some(inspect_idx)
99+
} else {
100+
smallest_violate_idx_so_far
101+
}
102+
})
104103
{
105-
(violate_idx..i).rev().for_each(|idx| {
104+
(smallest_violate_idx..i).rev().for_each(|idx| {
106105
result.swap(idx, idx + 1);
107106
});
108107
}
@@ -118,7 +117,7 @@ fn p2(input: &str) -> String {
118117
updates
119118
.into_iter()
120119
.filter(|update| !is_valid_ordering(&rules, update))
121-
.map(|update| fix_page_orderings(&rules, &update))
120+
.map(|update| fix_page_ordering(&rules, &update))
122121
.map(|update| get_middle_page(&update))
123122
.sum::<usize>()
124123
.to_string()

0 commit comments

Comments
 (0)