hashmaps3.rs (2669B)
1 // A list of scores (one per line) of a soccer match is given. Each line is of 2 // the form "<team_1_name>,<team_2_name>,<team_1_goals>,<team_2_goals>" 3 // Example: "England,France,4,2" (England scored 4 goals, France 2). 4 // 5 // You have to build a scores table containing the name of the team, the total 6 // number of goals the team scored, and the total number of goals the team 7 // conceded. 8 9 use std::collections::HashMap; 10 11 // A structure to store the goal details of a team. 12 #[derive(Default)] 13 struct TeamScores { 14 goals_scored: u8, 15 goals_conceded: u8, 16 } 17 18 fn build_scores_table(results: &str) -> HashMap<&str, TeamScores> { 19 // The name of the team is the key and its associated struct is the value. 20 let mut scores = HashMap::<&str, TeamScores>::new(); 21 22 for line in results.lines() { 23 let mut split_iterator = line.split(','); 24 // NOTE: We use `unwrap` because we didn't deal with error handling yet. 25 let team_1_name = split_iterator.next().unwrap(); 26 let team_2_name = split_iterator.next().unwrap(); 27 let team_1_score: u8 = split_iterator.next().unwrap().parse().unwrap(); 28 let team_2_score: u8 = split_iterator.next().unwrap().parse().unwrap(); 29 30 // Insert the default with zeros if a team doesn't exist yet. 31 let team_1 = scores.entry(team_1_name).or_default(); 32 // Update the values. 33 team_1.goals_scored += team_1_score; 34 team_1.goals_conceded += team_2_score; 35 36 // Similarly for the second team. 37 let team_2 = scores.entry(team_2_name).or_default(); 38 team_2.goals_scored += team_2_score; 39 team_2.goals_conceded += team_1_score; 40 } 41 42 scores 43 } 44 45 fn main() { 46 // You can optionally experiment here. 47 } 48 49 #[cfg(test)] 50 mod tests { 51 use super::*; 52 53 const RESULTS: &str = "England,France,4,2 54 France,Italy,3,1 55 Poland,Spain,2,0 56 Germany,England,2,1 57 England,Spain,1,0"; 58 59 #[test] 60 fn build_scores() { 61 let scores = build_scores_table(RESULTS); 62 63 assert!( 64 ["England", "France", "Germany", "Italy", "Poland", "Spain"] 65 .into_iter() 66 .all(|team_name| scores.contains_key(team_name)) 67 ); 68 } 69 70 #[test] 71 fn validate_team_score_1() { 72 let scores = build_scores_table(RESULTS); 73 let team = scores.get("England").unwrap(); 74 assert_eq!(team.goals_scored, 6); 75 assert_eq!(team.goals_conceded, 4); 76 } 77 78 #[test] 79 fn validate_team_score_2() { 80 let scores = build_scores_table(RESULTS); 81 let team = scores.get("Spain").unwrap(); 82 assert_eq!(team.goals_scored, 0); 83 assert_eq!(team.goals_conceded, 3); 84 } 85 }