Skip to content

Instantly share code, notes, and snippets.

@drakhavik
Last active October 28, 2020 00:35
Show Gist options
  • Save drakhavik/722062547ed0d8dcaef1b3f802aa87d4 to your computer and use it in GitHub Desktop.
Save drakhavik/722062547ed0d8dcaef1b3f802aa87d4 to your computer and use it in GitHub Desktop.
hash-maps exercise
use std::collections::HashMap;
use std::io;
fn list_users(department: &str, user_map: &HashMap<String, Vec<String>>) {
if department == "All" || department == "all" {
for (key, value) in user_map {
println!("Department - {}:", key);
for user in value {
println!(" •{}", user);
}
}
} else {
let users = user_map.get(department);
match users {
Some(info) => {
for user in info {
println!(" •{}", user)
}
}
None => println!("Department doesn't exist, or it's empty!"),
}
}
}
fn main() {
// Using a hash map and vectors, create a text interface to allow
// a user to add employee names to a department in a company.
// For example, "Add Sally to Engineering" or "Add Amir to Sales."
// Then let the user retrieve a list of all people in a department
// or all people in the ompany by department sorted alphabetically
let mut user_map: HashMap<String, Vec<String>> = HashMap::new();
loop {
println!("Please enter a command: ");
// Expected commands: Add [name] to [department] || View [all || department]
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let input: Vec<&str> = input.trim().split(' ').collect();
let operator = input.get(0).map(|x| x.to_lowercase());
match operator.as_deref() {
Some("add") => match (input.get(1), input.get(3)) {
(Some(name), Some(department)) => {
let user_vec = user_map.entry(department.to_string()).or_insert(Vec::new());
user_vec.push(name.to_string());
user_vec.sort();
}
(None, Some(_)) => println!("Please enter a name!"),
(Some(_), None) => println!("Please enter a department!"),
(None, None) => println!("Please enter a name and department!"),
},
Some("view") => match input.get(1) {
Some(department) => list_users(department, &user_map),
None => println!("Please enter all or a department!"),
},
Some("exit") => break,
Some(_) | None => println!("Invalid command 😞"),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment