1
+ use std:: { collections:: { HashMap , HashSet } , io:: stdin} ;
2
+ use itertools:: Itertools ;
3
+
4
+ fn main ( ) {
5
+ let lines = stdin ( ) . lines ( ) . filter_map ( Result :: ok) . collect_vec ( ) ;
6
+
7
+ let mut all: Vec < & str > = Vec :: new ( ) ;
8
+ let mut possible = HashMap :: new ( ) ;
9
+
10
+ for line in & lines {
11
+ let ( left, right) = line. split_once ( " (contains " ) . unwrap ( ) ;
12
+ let ingredients: HashSet < & str > = left. split ( " " ) . collect ( ) ;
13
+ let allergens = right. trim_matches ( ')' ) . split ( ", " ) . collect_vec ( ) ;
14
+ all. extend ( & ingredients) ;
15
+
16
+ for allergen in allergens {
17
+ possible. entry ( allergen)
18
+ . or_insert ( ingredients. clone ( ) )
19
+ . retain ( |k| ingredients. contains ( k) )
20
+ }
21
+ }
22
+ println ! ( "{}" , all. iter( ) . filter( |k| !possible. values( ) . flatten( ) . contains( k) ) . count( ) ) ;
23
+
24
+ let mut pairings: HashMap < & str , & str > = HashMap :: new ( ) ;
25
+ while possible. len ( ) != pairings. len ( ) {
26
+ possible. iter ( )
27
+ . filter ( |( _, v) | v. len ( ) == 1 )
28
+ . for_each ( |( k, v) | { pairings. insert ( k, v. iter ( ) . next ( ) . unwrap ( ) ) ; } ) ;
29
+ possible. values_mut ( )
30
+ . for_each ( |v| v. retain ( |a| !pairings. values ( ) . contains ( a) ) )
31
+ }
32
+ println ! ( "{}" , pairings. iter( ) . sorted( ) . map( |( _, b) | b) . join( "," ) ) ;
33
+ }
0 commit comments