From 16b76d6e99478f7b6ee0d7a248163e884df3a6ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Tj=C3=A4der?= <henrik@tjaders.com> Date: Sun, 5 Nov 2017 19:13:35 +0100 Subject: [PATCH] Do the same but with HashMaps --- src/main.rs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index d8dc771..0e5826a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ extern crate rand; use std::io; -use std::vec::Vec; +use std::collections::HashMap; use std::cmp::Ordering; use rand::Rng; @@ -11,7 +11,7 @@ fn main() { let secret_number = rand::thread_rng().gen_range(1, 101); let mut tries_counter : u32 = 0; - let mut attempt_history = Vec::<(u32, String)>::new(); + let mut attempt_history = HashMap::new(); println!("The secret number is: {}", secret_number); @@ -31,7 +31,9 @@ fn main() { tries_counter += 1; - attempt_history.push((tries_counter, format!("{}", guess))); + //attempt_history.push((tries_counter, format!("{}", guess))); + attempt_history.insert(tries_counter, format!("{}", guess)); + match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), @@ -39,16 +41,11 @@ fn main() { Ordering::Equal => { println!("You win!"); println!("Total number of attempts: {}", tries_counter); - println!("Last entry first, maximum 3:"); - for (i, x) in attempt_history.iter().rev().enumerate() { + for x in attempt_history { println!("{:?}", x); - // Only print the 3 last (see .rev() above) - if i >= 2 { - break; - } - - } + println!("Since the HashMap does not push things onto a heap like +the Vec-type does, it will iterate over and print in the order items are found"); break; } } -- GitLab