Skip to content

Instantly share code, notes, and snippets.

@riginding
Last active August 21, 2019 20:06
Show Gist options
  • Save riginding/d9b804db9ea87ca8259a9965bc79bf96 to your computer and use it in GitHub Desktop.
Save riginding/d9b804db9ea87ca8259a9965bc79bf96 to your computer and use it in GitHub Desktop.
baseline version with comments
use std::io::{self, Read, Write, BufWriter}; // Bring some IO stuff into scope
use std::collections::HashMap; // Bring Hashmap into scope
fn main() { // special entry function
let mut buffer = String::new(); // Initialize a string
io::stdin().read_to_string(&mut buffer).ok(); // fill string with input from stdin
let mut words: HashMap<&str, usize> = HashMap::new(); // initialize HashMap
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);
}
// we gather all entries of the dictionary in a Vector of Tuples
// the first field is the word, the second the number of occurrences
let mut sortable: Vec<(&str, usize)> = words
.iter()
.map(|(word, count)| (*word, *count))
.collect();
sortable.sort_by_key(|a| a.0); //sort words
sortable.sort_by(|a, b| b.1.cmp(&a.1)); // sort occurences
let mut output = BufWriter::new(io::stdout());
for word in sortable {
writeln!(output, "{}\t{}", word.0, word.1).ok(); // output to stdout
}
}
#[inline] // this instructs the compiler to inline this function
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