Menu
CoddyTech

Collections Recap

Lesson 24 of 48 in Coddy's Rust for Python Developers course.

challenge icon

Challenge

Easy

Implement pub fn add(stock: &mut BTreeMap<String, usize>, name: &str) and pub fn remove(stock: &mut BTreeMap<String, usize>, name: &str) -> bool in stock.rs. Add increases a name's count, inserting one when absent. Remove returns false without changing anything if absent; otherwise decrement and return true, removing the key when its count reaches zero. Valid stock maps contain only positive counts. Input has zero or more lines, each +name or -name; names are nonempty, contain no whitespace, and may contain Unicode. solve starts with empty stock, applies commands in order and returns removed|entries, where removed counts successful removals and entries are sorted name=count pairs joined with commas. Use empty for no entries.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, stock.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let mut items = std::collections::BTreeMap::new();
stock::add(&mut items, "bolt"); stock::add(&mut items, "bolt");
stock::add(&mut items, "nut");
let unchanged = items.clone();
assert!(!stock::remove(&mut items, "absent"));
assert_eq!(items, unchanged);
assert!(stock::remove(&mut items, "bolt"));
assert_eq!(items.get("bolt"), Some(&1));
assert!(stock::remove(&mut items, "bolt"));
assert!(!items.contains_key("bolt"));
assert!(!stock::remove(&mut items, "bolt"));
assert_eq!(items.get("nut"), Some(&1));

    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}

All lessons in Rust for Python Developers

Practice on your own: Online Rust compiler