Skip to content

Instantly share code, notes, and snippets.

@JustinAzoff
Last active May 5, 2017 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinAzoff/8fdbd4ffb0db75223f7e3d54b31575cb to your computer and use it in GitHub Desktop.
Save JustinAzoff/8fdbd4ffb0db75223f7e3d54b31575cb to your computer and use it in GitHub Desktop.
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();
}
@JustinAzoff
Copy link
Author

error[E0308]: if and else have incompatible types
  --> src/main.rs:20:25
   |
20 |     let final_results = if max_rows > 0 { results.skip(n) } else { results };
   |                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::iter::Skip`, found struct `std::slice::Iter`
   |
   = note: expected type `std::iter::Skip<std::slice::Iter<'_, (&std::string::String, {integer})>>`
              found type `std::slice::Iter<'_, (&std::string::String, {integer})>`

error: aborting due to previous error

error: Could not compile `count`.

@JustinAzoff
Copy link
Author

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) };

@JustinAzoff
Copy link
Author

JustinAzoff commented May 5, 2017

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