Skip to content

Instantly share code, notes, and snippets.

@riginding
Created August 21, 2019 20:26
Show Gist options
  • Save riginding/794a9d005d7d7fc51a56786cf5eba742 to your computer and use it in GitHub Desktop.
Save riginding/794a9d005d7d7fc51a56786cf5eba742 to your computer and use it in GitHub Desktop.
bytearray solution
use std::io::{self, Read, Write, BufWriter};
use std::collections::HashMap;
fn main() {
let mut buffer = Vec::<u8>::new();
io::stdin().read_to_end(&mut buffer).ok();
let mut words: HashMap<&[u8], 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<(&[u8], usize)> = vec![];
let mut single: Vec<(&[u8], usize)> = vec![];
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());
unsafe {
for word in multiple {
writeln!(output, "{}\t{}", std::str::from_utf8_unchecked(word.0), word.1).ok();
}
for word in single {
writeln!(output, "{}\t{}", std::str::from_utf8_unchecked(word.0), word.1).ok();
}
}
}
#[inline]
fn is_whitespace(c: &u8) -> bool {
*c == b' ' || *c == b'\t' || *c == b'\n'
}
#[inline]
fn is_not_empty(s: &&[u8]) -> bool {
!s.is_empty()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment