Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
seperated singletons
use std::io::{self, Read, Write, BufWriter};
use std::collections::HashMap;
fn main() {
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).ok();
let mut words: HashMap<&str, usize> = HashMap::new();
for word in buffer.split(is_whitespace).filter(is_not_empty) {
if let Some(count) = words.get_mut(word) {
*count += 1;
continue;
}
words.insert(word, 1);
}
let mut multiple: Vec<(&str, usize)> = vec![];
let mut single: Vec<(&str, usize)> = vec![];
// we create split all words into two vectors,
// one with multiple occurences and one Vector
// with single occurences
for (word, count) in words.iter() {
if *count > 1 {
multiple.push((*word, *count));
} else {
single.push((*word, *count));
}
}
multiple.sort_by_key(|a| a.0);
multiple.sort_by(|a, b| b.1.cmp(&a.1));
single.sort_by_key(|a| a.0);
let mut output = BufWriter::new(io::stdout());
for word in multiple {
writeln!(output, "{}\t{}", word.0, word.1).ok();
}
for word in single {
writeln!(output, "{}\t{}", word.0, word.1).ok();
}
}
#[inline]
fn is_not_empty(s: &&str) -> bool {
!s.is_empty()
}
#[inline]
fn is_whitespace(c: char) -> bool {
c == ' ' || c == '\t' || c == '\n'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment