Menu
CoddyTech

Maps and Sets

Lesson 23 of 48 in Coddy's Rust for Dart Developers course.

A Dart map literal preserves insertion order. Rust BTreeMap instead iterates keys in sorted order, so the programs intentionally print different orders for the same two entries. A Rust HashMap does not promise sorted iteration; choose the collection from the reporting contract. Dart's nullable lookup result can represent a missing key, and containsKey distinguishes absence from a stored null when nullable values are allowed. Rust get returns Option containing a borrowed value. Sets similarly represent unique keys without associated values. Changing collection implementations can change observable output even when lookups still succeed. Sort deliberately when ordering matters instead of relying on incidental traversal behavior.

Complete standalone Dart program:

void main() {
  final colors = <String, int>{};
  colors['zinc'] = 1;
  colors['amber'] = 2;
  print(colors.keys.join(','));
}

Dart output:

zinc,amber

Complete standalone Rust program:

use std::collections::BTreeMap;
fn main() {
    let mut colors = BTreeMap::new();
    colors.insert("zinc", 1);
    colors.insert("amber", 2);
    let names: Vec<&str> = colors.keys().copied().collect();
    println!("{}", names.join(","));
}

Rust output:

amber,zinc
challenge icon

Challenge

Easy

Implement pub fn frequencies(text: &str) -> BTreeMap<String, usize> and pub fn repeated(text: &str) -> BTreeSet<String> in vocabulary.rs, importing both types from std::collections. Split text on whitespace, compare words case-sensitively and retain punctuation. Frequencies counts every occurrence; repeated contains exactly words whose count is at least two. solve returns repeated words in sorted order as word=count, separated by commas; return none if the set is empty. Both APIs must handle empty input and independent calls with no retained global state.

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, vocabulary.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 vocabulary;
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 counts = vocabulary::frequencies("fern oak fern elm oak fern");
assert_eq!(counts.len(), 3);
assert_eq!(counts.get("fern"), Some(&3));
assert_eq!(counts.get("elm"), Some(&1));
assert_eq!(counts.get("missing"), None);
let repeated = vocabulary::repeated("fern oak fern elm oak fern");
assert_eq!(repeated.into_iter().collect::<Vec<_>>(), vec![String::from("fern"), String::from("oak")]);
assert!(vocabulary::frequencies("").is_empty());
assert!(vocabulary::repeated("single").is_empty());
assert_eq!(vocabulary::frequencies("A a").len(), 2);

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

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Dart Developers

Practice on your own: Online Rust compiler