1- #[ derive( Debug ) ]
1+ use std:: collections:: HashMap ;
2+
3+ #[ derive( Debug , PartialEq ) ]
24pub enum Category {
35 Ones ,
46 Twos ,
@@ -17,5 +19,53 @@ pub enum Category {
1719type Dice = [ u8 ; 5 ] ;
1820
1921pub fn score ( dice : Dice , category : Category ) -> u8 {
20- todo ! ( "determine the score for {dice:?} in the {category:?}" ) ;
22+ match category {
23+ Category :: Ones => dice. iter ( ) . filter ( |& d| * d == 1 ) . sum :: < u8 > ( ) ,
24+ Category :: Twos => dice. iter ( ) . filter ( |& d| * d == 2 ) . sum :: < u8 > ( ) ,
25+ Category :: Threes => dice. iter ( ) . filter ( |& d| * d == 3 ) . sum :: < u8 > ( ) ,
26+ Category :: Fours => dice. iter ( ) . filter ( |& d| * d == 4 ) . sum :: < u8 > ( ) ,
27+ Category :: Fives => dice. iter ( ) . filter ( |& d| * d == 5 ) . sum :: < u8 > ( ) ,
28+ Category :: Sixes => dice. iter ( ) . filter ( |& d| * d == 6 ) . sum :: < u8 > ( ) ,
29+ Category :: FullHouse | Category :: FourOfAKind | Category :: Yacht => {
30+ let mut counts: HashMap < u8 , u8 > = HashMap :: new ( ) ;
31+
32+ for dice_draw in dice {
33+ * counts. entry ( dice_draw) . or_insert ( 0 ) += 1 ;
34+ }
35+
36+ let mut occurences: Vec < u8 > = counts. values ( ) . copied ( ) . collect ( ) ;
37+ occurences. sort ( ) ;
38+
39+ if occurences == [ 2 , 3 ] && category == Category :: FullHouse {
40+ dice. iter ( ) . sum ( )
41+ } else if ( occurences == [ 1 , 4 ] || occurences == [ 5 ] )
42+ && category == Category :: FourOfAKind
43+ {
44+ let key_four_time = counts
45+ . iter ( )
46+ . find ( |& ( _, & v) | v == * occurences. iter ( ) . max ( ) . unwrap ( ) )
47+ . map ( |( & k, _) | k)
48+ . unwrap ( ) ;
49+
50+ key_four_time * 4
51+ } else if occurences == [ 5 ] && category == Category :: Yacht {
52+ 50
53+ } else {
54+ 0
55+ }
56+ }
57+ Category :: LittleStraight | Category :: BigStraight => {
58+ let mut dice = dice;
59+ dice. sort ( ) ;
60+
61+ if ( dice == [ 1 , 2 , 3 , 4 , 5 ] && category == Category :: LittleStraight )
62+ || ( dice == [ 2 , 3 , 4 , 5 , 6 ] && category == Category :: BigStraight )
63+ {
64+ 30
65+ } else {
66+ 0
67+ }
68+ }
69+ Category :: Choice => dice. iter ( ) . sum :: < u8 > ( ) ,
70+ }
2171}
0 commit comments