Skip to content

Instantly share code, notes, and snippets.

@TheCreatorAMA
Created August 23, 2022 16:05
Show Gist options
  • Save TheCreatorAMA/5e7b5d4063cb85de505aa039baed7f72 to your computer and use it in GitHub Desktop.
Save TheCreatorAMA/5e7b5d4063cb85de505aa039baed7f72 to your computer and use it in GitHub Desktop.
Rust chapter 8 exercise, add employee names to a department in a company (hashmaps and vectors)
use std::collections::HashMap;
use itertools::Itertools;
use std::io;
fn main() {
// command must be in format of "add <name> to <department>" or "get <department>". Command
// must start with add or get. For the "get" command, "get all" will get all employees from
// each department sorted in alphabetical order by department.
let mut employee_data = HashMap::new();
'input_loop: loop {
println!("Please enter the command you would like to execute: ");
let mut user_input = String::new();
io::stdin()
.read_line(&mut user_input)
.expect("Failed to read line");
let mut count: u32 = 0;
let mut command_length: u32 = 0;
let mut name = String::new();
let mut department = String::new();
for word in user_input.split_whitespace() {
if count == 0 {
match word {
"add" => {
command_length = 4;
}
"get" => {
command_length = 2;
}
_ => {
println!("Invalid command, must be get or add.");
break 'input_loop;
}
}
} else {
match command_length {
4 => {
if count == 1 {
name = word.to_string();
} else if count == 3 {
department = word.to_string();
}
}
2 => {
if count == 1 {
department = word.to_string();
} else {
continue;
}
}
_ => panic!("Error"),
}
}
count += 1;
}
if command_length == 4 {
println!("Employee {} was added to the {} department", name, department);
employee_data.entry(department).or_insert(Vec::new()).push(name);
} else if command_length == 2 {
if department == "all" {
for (key, val) in employee_data.iter().sorted() {
for item in val {
println!("{:?} in {:?}", item, key);
}
}
} else {
println!("{:?}", employee_data.get(&department));
}
}
}
}
@TheCreatorAMA
Copy link
Author

Feel free to leave feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment