Menu
CoddyTech

Maps and Sets

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

A JavaScript Map iterates its entries in insertion order, and Set does the same for its values. Keys are compared with SameValueZero, so strings and numbers match by value, but two arrays or objects with equal contents are different keys. Rust BTreeMap and BTreeSet iterate in sorted key order instead, and HashMap and HashSet promise no order at all. Rust keys are compared by value through traits such as Ord or Eq, so equal strings or vectors are the same key. Choosing a collection therefore changes the output order even when the inserted data is identical. The examples count words inserted as zinc, amber, zinc: JavaScript reports them in first-seen order, Rust alphabetically. A missing key gives undefined from Map.prototype.get, which is ambiguous when undefined could also be a stored value. Rust get returns an Option, so absence is a separate case you must handle. The entry API inserts a starting count or updates the existing one in a single lookup. A set stores unique keys with no mapped value, which suits a list of words seen more than once.

Complete standalone JavaScript program:

const counts = new Map();
for (const word of "zinc amber zinc".split(" ")) {
  counts.set(word, (counts.get(word) ?? 0) + 1);
}
console.log([...counts].map(([w, n]) => `${w}=${n}`).join(","));
console.log(counts.get("teal"));

JavaScript output:

zinc=2,amber=1
undefined

Complete standalone Rust program:

use std::collections::BTreeMap;
fn main() {
    let mut counts = BTreeMap::new();
    for word in "zinc amber zinc".split(' ') {
        *counts.entry(word).or_insert(0) += 1;
    }
    println!("{:?}", counts);
    println!("{:?}", counts.get("teal"));
}

Rust output:

{"amber": 1, "zinc": 2}
None
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 JavaScript Developers

Practice on your own: Online Rust compiler