RustArena

Step 6 of 7

dedup, retain, contains and binary_search

Real data is messy: duplicate entries, invalid readings, things you need to look up. Vectors have tools for each.

fn main() {
    let mut visitors = vec![42, 7, 42, 42, 13, 7];
    visitors.dedup();
    println!("{:?}", visitors);
    visitors.sort();
    visitors.dedup();
    println!("{:?}", visitors);

    let mut readings = vec![12, -1, 15, -1, 9];
    readings.retain(|&r| r >= 0);
    println!("{:?}", readings);

    println!("{}", visitors.contains(&13));
    println!("{:?} {:?}", visitors.binary_search(&13), visitors.binary_search(&10));
}
[42, 7, 42, 13, 7]
[7, 13, 42]
[12, 15, 9]
true
Ok(1) Err(1)

Piece by piece:

Common mistakes

Your task

Write fn clean_log(lines: &mut Vec<String>) that removes every line containing "DEBUG" and then collapses consecutive identical lines into one (a service that retries prints the same line many times in a row).

Challenge 2

A sorted list of user ids must stay sorted and unique. Write fn insert_unique(sorted: &mut Vec<u32>, id: u32) -> bool with binary_search: if the id is already there return false and change nothing; otherwise insert it at the position binary_search reports and return true.

Challenge 3

Build a guest list. Read names, one per line. Trim spaces around each name, ignore blank lines, treat names case-insensitively (store them in lowercase), and print the unique names in alphabetical order, one per line, followed by N unique guests.

Previous: Sorting Next: A Vec of structs