Skip to content

Instantly share code, notes, and snippets.

@pftbest
Created June 8, 2017 17:00
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 pftbest/ffef0fb4a478653e5e40bb9ec7ff8c29 to your computer and use it in GitHub Desktop.
Save pftbest/ffef0fb4a478653e5e40bb9ec7ff8c29 to your computer and use it in GitHub Desktop.
use std::str;
use std::process;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::collections::HashMap;
fn main() {
let mut args = std::env::args();
if args.len() < 4 {
let prog = args.next().unwrap();
println!("synopsis: {} file_name key_field value_field", prog);
process::exit(-1);
}
let file_name = args.nth(1).unwrap();
let key_field: usize = args.next().unwrap().parse().unwrap();
let value_field: usize = args.next().unwrap().parse().unwrap();
let max_field = std::cmp::max(key_field, value_field);
let file = File::open(file_name).unwrap();
let mut reader = BufReader::new(file);
let mut map = HashMap::new();
let mut line = Vec::with_capacity(100);
while reader.read_until('\n' as u8, &mut line).unwrap() > 0 {
line.pop();
{
let parts = line.split(|&c| c == '\t' as u8);
let mut key = None;
let mut val = None;
for (i, p) in parts.enumerate() {
if i == key_field {
key = Some(p);
}
if i == value_field {
val = Some(p)
}
if i == max_field {
break;
}
}
if let (Some(key), Some(val)) = (key, val) {
let num: u64 = str::from_utf8(val).unwrap().parse().unwrap();
upsert(&mut map, key, num);
}
}
line.clear();
}
if let Some((key, val)) = map.iter().max_by_key(|&(_, v)| v) {
println!("max_key: {} sum: {}", str::from_utf8(key).unwrap(), val);
} else {
println!("No entries");
}
}
fn upsert(map: &mut HashMap<Vec<u8>, u64>, key: &[u8], val: u64) {
if let Some(entry) = map.get_mut(key) {
*entry += val;
return;
}
map.insert(key.to_owned(), val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment