Skip to content

Instantly share code, notes, and snippets.

@djhworld
Created December 30, 2018 10:55

Revisions

  1. djhworld renamed this gist Dec 30, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. djhworld created this gist Dec 30, 2018.
    87 changes: 87 additions & 0 deletions count.rs improved
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    use std::collections::HashMap;
    use std::io;
    use std::io::BufRead;

    struct Counter {
    items: HashMap<String, usize>,
    }

    impl Counter {
    fn new() -> Counter {
    return Counter {
    items: HashMap::new(),
    };
    }
    fn add(&mut self, st: &str) {
    match self.items.get_mut(st) {
    Some(x) => {
    *x += 1;
    }
    None => {
    self.items.insert(st.to_owned(), 1);
    }
    }
    }

    fn render(&self) {
    for (key, val) in &self.items {
    println!("{}\t{}", val, key);
    }
    }
    }

    fn using_read_line_with_reuse(c: &mut Counter) {
    let st = io::stdin();
    let mut stdin = st.lock();
    let mut line = String::new();

    loop {
    line.clear();
    let r = stdin.read_line(&mut line);
    match r {
    Ok(0) => break,
    Ok(_) => {
    c.add(line.trim_end());
    }
    Err(err) => {
    println!("{}", err);
    break;
    }
    };
    }
    }

    fn using_read_line(c: &mut Counter) {
    let st = io::stdin();
    let mut stdin = st.lock();

    loop {
    let mut line = String::new();
    let r = stdin.read_line(&mut line);
    match r {
    Ok(0) => break,
    Ok(_) => {
    c.add(line.trim_end());
    }
    Err(err) => {
    println!("{}", err);
    break;
    }
    };
    }
    }

    // uses lines() iterator
    fn using_bufread_lines(c: &mut Counter) {
    for r in io::stdin().lock().lines().filter_map(Result::ok) {
    c.add(r.as_str());
    }
    }

    fn main() {
    let mut c = Counter::new();
    // using_bufread_lines(&mut c);
    //using_read_line(&mut c);
    using_read_line_with_reuse(&mut c);
    c.render();
    }