Created
August 24, 2019 11:20
-
-
Save riginding/6e809ff4a1fa5298592cee77f5ce6643 to your computer and use it in GitHub Desktop.
vecs have set capacity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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::with_capacity(words.len()); | |
let mut single: Vec<(&[u8], usize)> = Vec::with_capacity(words.len()); | |
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