Tuple Keys Track Pair Occurrences
Use tuple keys in HashMap to count consecutive character pairs; derive ordering by collecting and sorting entries for stable output.
Code
use std::collections::HashMap;
fn main() {
let text = "abcaabb";
let chars: Vec<char> = text.chars().collect();
// 元组作复合键:(char, char) 自动实现 Hash 与 Eq
let mut pairs: HashMap<(char, char), u32> = HashMap::new();
for w in chars.windows(2) {
*pairs.entry((w[0], w[1])).or_insert(0) += 1; // occurrence counts
}
// HashMap 遍历顺序不保证:收集后按键排序输出才可复现
let mut items: Vec<_> = pairs.into_iter().collect();
items.sort_by(|a, b| a.0.cmp(&b.0));
for ((a, b), n) in items {
println!("{a}{b}: {n}");
}
}What the code does
Tuple Keys Track Pair Occurrences is built around the function main.
A single loop drives the file — for w in chars.windows(2).
Iteration is driven by for w in chars.windows(2) and for ((a, b), n) in items.
Statements that matter
let mut items: Vec<_> = pairs.into_iter().collect();
let chars: Vec<char> = text.chars().collect();
Interactive Tools for This Topic
FAQ
- How do you run Tuple Keys Track Pair Occurrences?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.