5
5
//! maximize speed we'll instead hand code validation functions for each of the
6
6
//! passport field criteria.
7
7
use crate :: util:: iter:: * ;
8
+ use crate :: util:: parse:: * ;
8
9
use std:: ops:: RangeInclusive ;
9
10
10
- type Passport < ' a > = Vec < [ & ' a str ; 2 ] > ;
11
+ type Input = ( u32 , u32 ) ;
11
12
12
- pub fn parse ( input : & str ) -> Vec < Passport < ' _ > > {
13
- input. split ( "\n \n " ) . map ( parse_block) . collect ( )
14
- }
13
+ pub fn parse ( input : & str ) -> Input {
14
+ let mut passport = Vec :: new ( ) ;
15
+ let mut part_one = 0 ;
16
+ let mut part_two = 0 ;
17
+
18
+ for block in input. split ( "\n \n " ) {
19
+ parse_block ( & mut passport, block) ;
20
+
21
+ if passport. len ( ) == 7 {
22
+ part_one += 1 ;
23
+ part_two += passport. iter ( ) . all ( validate_field) as u32 ;
24
+ }
15
25
16
- pub fn part1 ( input : & [ Passport < ' _ > ] ) -> usize {
17
- input. iter ( ) . filter ( |passport| passport. len ( ) == 7 ) . count ( )
26
+ passport. clear ( ) ;
27
+ }
28
+
29
+ ( part_one, part_two)
18
30
}
19
31
20
- pub fn part2 ( input : & [ Passport < ' _ > ] ) -> usize {
21
- input
22
- . iter ( )
23
- . filter ( |passport| passport. len ( ) == 7 )
24
- . filter ( |passport| passport. iter ( ) . all ( validate_field) )
25
- . count ( )
32
+ pub fn part1 ( input : & Input ) -> u32 {
33
+ input. 0
26
34
}
27
35
28
- fn parse_block ( block : & str ) -> Passport < ' _ > {
29
- let mut fields = Vec :: with_capacity ( 7 ) ;
36
+ pub fn part2 ( input : & Input ) -> u32 {
37
+ input. 1
38
+ }
30
39
40
+ fn parse_block < ' a > ( passport : & mut Vec < [ & ' a str ; 2 ] > , block : & ' a str ) {
31
41
for pair @ [ key, _] in block. split ( [ ':' , ' ' , '\n' ] ) . chunk :: < 2 > ( ) {
32
42
if key != "cid" {
33
- fields . push ( pair) ;
43
+ passport . push ( pair) ;
34
44
}
35
45
}
36
-
37
- fields
38
46
}
39
47
40
48
fn validate_field ( & [ key, value] : & [ & str ; 2 ] ) -> bool {
@@ -51,7 +59,7 @@ fn validate_field(&[key, value]: &[&str; 2]) -> bool {
51
59
}
52
60
53
61
fn validate_range ( s : & str , range : RangeInclusive < u32 > ) -> bool {
54
- s . parse ( ) . is_ok_and ( |n| range. contains ( & n ) )
62
+ range. contains ( & s . unsigned ( ) )
55
63
}
56
64
57
65
fn validate_height ( hgt : & str ) -> bool {
0 commit comments