Skip to content

Instantly share code, notes, and snippets.

@tupshin
Created December 23, 2014 18:14
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 tupshin/6ec681125e98444684ef to your computer and use it in GitHub Desktop.
Save tupshin/6ec681125e98444684ef to your computer and use it in GitHub Desktop.
use std::io::{BufferedReader,File};
use std::collections::BinaryHeap; //latest nightlies have switch renamed PriorityQueue to BinaryHeap
fn main() {
let n = 3u; // n longest lines.
let path = Path::new("test.txt");
let mut file = BufferedReader::new(File::open(&path));
let mut pq = BinaryHeap::new(); // note: max-heap. See above about BinaryHeap
for (i, line) in file.lines().enumerate() {
let contents = line.unwrap();
let neg_line_length:i32 = -(contents.len() as i32); // simulate min-heap. need to negate after casting, since contents.len
let element = (neg_line_length, contents);
if i <= n { // push first n lines onto
pq.push(element); // heap unconditionally.
} else {
let curr_min = pq.top().unwrap().clone(); // thereafter, add line. The clone() call addresses your actual problem
let (neg_curr_min_length, _) = curr_min; // to heap only if its
if neg_line_length < neg_curr_min_length { // length greater than
pq.push_pop(element); // current heap minimum.
}
}
}
for item in pq.into_sorted_vec().iter() {
println!("{}:{}", -item.0, item.1); //undo your negation and gives your formatting flexbility by accessing the elements of your tuple separately
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment