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