File tree Expand file tree Collapse file tree 1 file changed +17
-23
lines changed Expand file tree Collapse file tree 1 file changed +17
-23
lines changed Original file line number Diff line number Diff line change 1
1
//! # Inventory Management System
2
2
3
+ use crate :: util:: hash:: * ;
4
+
3
5
pub fn parse ( input : & str ) -> Vec < & [ u8 ] > {
4
6
input. lines ( ) . map ( str:: as_bytes) . collect ( )
5
7
}
@@ -43,33 +45,25 @@ pub fn part1(input: &[&[u8]]) -> u32 {
43
45
}
44
46
45
47
pub fn part2 ( input : & [ & [ u8 ] ] ) -> String {
46
- // Manually compare all IDs, as it is faster than other methods considering there are so few total IDs
47
- for i in 0 ..input. len ( ) {
48
- for ii in i + 1 ..input. len ( ) {
49
- let id1 = input[ i] ;
50
- let id2 = input[ ii] ;
48
+ let width = input[ 0 ] . len ( ) ;
51
49
52
- let mut diff = false ;
53
- for ( a, b) in id1. iter ( ) . zip ( id2) {
54
- if a != b {
55
- if diff {
56
- diff = false ;
57
- break ;
58
- }
59
- diff = true ;
60
- }
61
- }
50
+ let mut seen = FastSet :: with_capacity ( input. len ( ) ) ;
62
51
63
- if diff {
64
- // Build the string of characters which are the same between both IDs
65
- return id1
66
- . iter ( )
67
- . zip ( id2)
68
- . filter ( |& ( a, b) | a == b)
69
- . map ( |( a, _) | char:: from ( * a) )
70
- . collect ( ) ;
52
+ // Use a set to check for duplicates by comparing the prefix and suffix of IDs excluding one
53
+ // column at a time.
54
+ for column in 0 ..width {
55
+ for & id in input {
56
+ let prefix = & id[ ..column] ;
57
+ let suffix = & id[ column + 1 ..] ;
58
+
59
+ if !seen. insert ( [ prefix, suffix] ) {
60
+ // Convert to String
61
+ return prefix. iter ( ) . chain ( suffix) . cloned ( ) . map ( char:: from) . collect ( ) ;
71
62
}
72
63
}
64
+
65
+ seen. clear ( ) ;
73
66
}
67
+
74
68
unreachable ! ( )
75
69
}
You can’t perform that action at this time.
0 commit comments