File tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Original file line number Diff line number Diff line change 1+ 3 4
2+ 4 3
3+ 2 5
4+ 1 3
5+ 3 9
6+ 3 3
Original file line number Diff line number Diff line change 1+ use advent_of_code:: maneatingape:: {
2+ hash:: { FastMap , FastMapBuilder } ,
3+ parse:: * ,
4+ } ;
5+
6+ advent_of_code:: solution!( 1 ) ;
7+
8+ fn parse_data ( input : & str ) -> ( Vec < u32 > , Vec < u32 > ) {
9+ let first = input
10+ . lines ( )
11+ . map ( |line| line. iter_unsigned ( ) . next ( ) . unwrap ( ) )
12+ . collect ( ) ;
13+ let second = input
14+ . lines ( )
15+ . map ( |line| line. iter_unsigned ( ) . nth ( 1 ) . unwrap ( ) )
16+ . collect ( ) ;
17+
18+ ( first, second)
19+ }
20+
21+ pub fn part_one ( input : & str ) -> Option < u32 > {
22+ let ( mut left, mut right) = parse_data ( input) ;
23+
24+ left. sort_unstable ( ) ;
25+ right. sort_unstable ( ) ;
26+
27+ let result = left
28+ . into_iter ( )
29+ . zip ( right)
30+ . map ( |( x, y) | u32:: abs_diff ( x, y) )
31+ . sum ( ) ;
32+
33+ Some ( result)
34+ }
35+
36+ pub fn part_two ( input : & str ) -> Option < u32 > {
37+ let ( left, right) = parse_data ( input) ;
38+
39+ let mut right_counter = FastMap :: new ( ) ;
40+ for item in right {
41+ * right_counter. entry ( item) . or_default ( ) += 1 ;
42+ }
43+
44+ let result = left
45+ . into_iter ( )
46+ . map ( |x| match right_counter. get ( & x) {
47+ Some ( v) => x * v,
48+ None => 0 ,
49+ } )
50+ . sum ( ) ;
51+
52+ Some ( result)
53+ }
54+
55+ #[ cfg( test) ]
56+ mod tests {
57+ use super :: * ;
58+
59+ #[ test]
60+ fn test_part_one ( ) {
61+ let result = part_one ( & advent_of_code:: template:: read_file ( "examples" , DAY ) ) ;
62+ assert_eq ! ( result, Some ( 11 ) ) ;
63+ }
64+
65+ #[ test]
66+ fn test_part_two ( ) {
67+ let result = part_two ( & advent_of_code:: template:: read_file ( "examples" , DAY ) ) ;
68+ assert_eq ! ( result, Some ( 31 ) ) ;
69+ }
70+ }
You can’t perform that action at this time.
0 commit comments