Last active
May 5, 2017 22:54
-
-
Save JustinAzoff/8fdbd4ffb0db75223f7e3d54b31575cb to your computer and use it in GitHub Desktop.
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::collections::HashMap; | |
use std::io::{self, BufRead, BufWriter}; | |
use std::io::Write; | |
fn count(max_rows: usize) -> Result<(), io::Error> { | |
let stdin = io::stdin(); | |
let mut counts = HashMap::new(); | |
for line in stdin.lock().lines() { | |
let l = line.unwrap(); | |
let stat = counts.entry(l).or_insert(0); | |
*stat += 1; | |
} | |
let mut pop: Vec<_> = counts.iter().map(|(k, &v)| (k, v)).collect(); | |
//pop.sort_by(|&(_, c1), &(_, c2)| c2.cmp(&c1)); | |
pop.sort_by_key(|t| t.1); | |
let mut writer = BufWriter::new(io::stdout()); | |
let results = pop.iter(); | |
let n = results.len() - max_rows; | |
let final_results = if max_rows > 0 { results.skip(n) } else { results }; | |
for &(k, v) in final_results { | |
writer.write(k.as_bytes())?; | |
writer.write(b"\t")?; | |
writer.write(v.to_string().as_bytes())?; | |
writer.write(b"\n")?; | |
} | |
Ok(()) | |
} | |
fn main() { | |
count(10).unwrap(); | |
} |
Author
JustinAzoff
commented
May 5, 2017
Fixed version does
let n = if max_rows > results.len() { 0 } else { results.len() - max_rows };
let final_results = if max_rows > 0 { results.skip(n) } else { results.skip(0) };
and at that point.. max_rows can just default to 0. I had it as .take() before with the results reversed. so not reversing simplifies things.
I think my next issue is adding back in the .reverse() conditionally
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment