hashmaps3.rs (2778B)
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 // TODO: Populate the scores table with the extracted details. 31 // Keep in mind that goals scored by team 1 will be the number of goals 32 // conceded by team 2. Similarly, goals scored by team 2 will be the 33 // number of goals conceded by team 1. 34 let t1 = scores.entry(team_1_name).or_default(); 35 t1.goals_scored += team_1_score; 36 t1.goals_conceded += team_2_score; 37 38 let t2 = scores.entry(team_2_name).or_default(); 39 t2.goals_scored += team_2_score; 40 t2.goals_conceded += team_1_score; 41 } 42 43 scores 44 } 45 46 fn main() { 47 // You can optionally experiment here. 48 } 49 50 #[cfg(test)] 51 mod tests { 52 use super::*; 53 54 const RESULTS: &str = "England,France,4,2 55 France,Italy,3,1 56 Poland,Spain,2,0 57 Germany,England,2,1 58 England,Spain,1,0"; 59 60 #[test] 61 fn build_scores() { 62 let scores = build_scores_table(RESULTS); 63 64 assert!( 65 ["England", "France", "Germany", "Italy", "Poland", "Spain"] 66 .into_iter() 67 .all(|team_name| scores.contains_key(team_name)) 68 ); 69 } 70 71 #[test] 72 fn validate_team_score_1() { 73 let scores = build_scores_table(RESULTS); 74 let team = scores.get("England").unwrap(); 75 assert_eq!(team.goals_scored, 6); 76 assert_eq!(team.goals_conceded, 4); 77 } 78 79 #[test] 80 fn validate_team_score_2() { 81 let scores = build_scores_table(RESULTS); 82 let team = scores.get("Spain").unwrap(); 83 assert_eq!(team.goals_scored, 0); 84 assert_eq!(team.goals_conceded, 3); 85 } 86 }