11use crate :: solutions:: Solution ;
22use itertools:: Itertools ;
3- use std:: cmp:: Ordering :: Equal ;
43use std:: collections:: HashMap ;
54
65pub struct Day04 ;
@@ -46,7 +45,7 @@ impl<'a> From<&'a str> for Room<'a> {
4645 Self {
4746 checksum,
4847 sector_id : number,
49- encrypted_parts : rest. into ( ) ,
48+ encrypted_parts : rest. to_vec ( ) ,
5049 }
5150 }
5251}
@@ -57,25 +56,21 @@ impl<'a> Room<'a> {
5756 }
5857
5958 fn calculate_checksum ( & self ) -> String {
60- let mut map : HashMap < char , u8 > = HashMap :: new ( ) ;
59+ let mut counts : HashMap < char , u32 > = HashMap :: new ( ) ;
6160
62- for r in self . encrypted_parts . iter ( ) {
63- for c in r. chars ( ) {
64- * map. entry ( c) . or_insert ( 0 ) += 1 ;
65- }
66- }
67-
68- let mut items: Vec < _ > = map. iter ( ) . collect ( ) ;
69- items. sort_by ( |( a_k, a_v) , ( b_k, b_v) | {
70- // First compare by value
71- match b_v. cmp ( a_v) {
72- // And by key
73- Equal => a_k. cmp ( b_k) ,
74- other => other,
75- }
76- } ) ;
77-
78- items. iter ( ) . take ( 5 ) . map ( |( k, _) | * k) . collect :: < String > ( )
61+ self . encrypted_parts
62+ . iter ( )
63+ . flat_map ( |s| s. chars ( ) )
64+ . for_each ( |c| * counts. entry ( c) . or_insert ( 0 ) += 1 ) ;
65+
66+ counts
67+ . into_iter ( )
68+ . sorted_by ( |( a_char, a_count) , ( b_char, b_count) | {
69+ b_count. cmp ( a_count) . then_with ( || a_char. cmp ( b_char) )
70+ } )
71+ . take ( 5 )
72+ . map ( |( c, _) | c)
73+ . collect ( )
7974 }
8075
8176 fn decrypt ( & self ) -> String {
0 commit comments