Skip to content
Snippets Groups Projects
Commit 16b76d6e authored by Henrik Tjäder's avatar Henrik Tjäder
Browse files

Do the same but with HashMaps

parent 19df3cce
No related branches found
No related tags found
No related merge requests found
extern crate rand; extern crate rand;
use std::io; use std::io;
use std::vec::Vec; use std::collections::HashMap;
use std::cmp::Ordering; use std::cmp::Ordering;
use rand::Rng; use rand::Rng;
...@@ -11,7 +11,7 @@ fn main() { ...@@ -11,7 +11,7 @@ fn main() {
let secret_number = rand::thread_rng().gen_range(1, 101); let secret_number = rand::thread_rng().gen_range(1, 101);
let mut tries_counter : u32 = 0; 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); println!("The secret number is: {}", secret_number);
...@@ -31,7 +31,9 @@ fn main() { ...@@ -31,7 +31,9 @@ fn main() {
tries_counter += 1; 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) { match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"), Ordering::Less => println!("Too small!"),
...@@ -39,16 +41,11 @@ fn main() { ...@@ -39,16 +41,11 @@ fn main() {
Ordering::Equal => { Ordering::Equal => {
println!("You win!"); println!("You win!");
println!("Total number of attempts: {}", tries_counter); println!("Total number of attempts: {}", tries_counter);
println!("Last entry first, maximum 3:"); for x in attempt_history {
for (i, x) in attempt_history.iter().rev().enumerate() {
println!("{:?}", x); 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; break;
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment