@@ -2,7 +2,6 @@ use std::collections::{HashMap, HashSet};
2
2
3
3
const ACTUAL_INPUT : & str = include_str ! ( "../../../actual_inputs/2024/05/input.txt" ) ;
4
4
5
- #[ derive( Clone ) ]
6
5
struct Graph {
7
6
children : HashMap < usize , HashSet < usize > > ,
8
7
}
@@ -57,13 +56,12 @@ fn is_valid_ordering(rules: &Graph, update: &[usize]) -> bool {
57
56
let mut seen = HashSet :: new ( ) ;
58
57
59
58
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
- }
65
59
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 )
67
65
} ) ;
68
66
69
67
!found_violated_order
@@ -84,25 +82,26 @@ fn p1(input: &str) -> String {
84
82
. to_string ( )
85
83
}
86
84
87
- fn fix_page_orderings ( rules : & Graph , update : & [ usize ] ) -> Vec < usize > {
85
+ fn fix_page_ordering ( rules : & Graph , update : & [ usize ] ) -> Vec < usize > {
88
86
let mut result = update. to_vec ( ) ;
89
87
90
88
let empty_hashset = HashSet :: new ( ) ;
91
89
92
90
for i in 0 ..result. len ( ) {
93
91
let children = rules. children . get ( & result[ i] ) . unwrap_or ( & empty_hashset) ;
94
92
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
+ } )
104
103
{
105
- ( violate_idx ..i) . rev ( ) . for_each ( |idx| {
104
+ ( smallest_violate_idx ..i) . rev ( ) . for_each ( |idx| {
106
105
result. swap ( idx, idx + 1 ) ;
107
106
} ) ;
108
107
}
@@ -118,7 +117,7 @@ fn p2(input: &str) -> String {
118
117
updates
119
118
. into_iter ( )
120
119
. filter ( |update| !is_valid_ordering ( & rules, update) )
121
- . map ( |update| fix_page_orderings ( & rules, & update) )
120
+ . map ( |update| fix_page_ordering ( & rules, & update) )
122
121
. map ( |update| get_middle_page ( & update) )
123
122
. sum :: < usize > ( )
124
123
. to_string ( )
0 commit comments