From c4ffde4ed6d42e80b438f7cef9c2b30a6b6a0513 Mon Sep 17 00:00:00 2001 From: Marco Romano Date: Fri, 20 Jan 2023 08:39:56 +0100 Subject: [PATCH] Week1 exercise Submitting this as a PR for completeness even though it's been already shared via gists. --- week1/src/main.rs | 52 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/week1/src/main.rs b/week1/src/main.rs index a61674c..fb387d8 100644 --- a/week1/src/main.rs +++ b/week1/src/main.rs @@ -1,23 +1,49 @@ -use std::{cmp::Ordering, collections::HashMap, io}; +use rand::Rng; +use std::cmp::Ordering; +use std::io; fn main() { - let secret_number = 5; + println!("Guess the number!"); - let mut guess = String::new(); + let secret_number = rand::thread_rng().gen_range(1..=10); - println!("Guess the number!"); + println!("The secret number is: {secret_number}"); + + loop { + println!("Please input your guess."); + + let mut guess = String::new(); - io::stdin() - .read_line(&mut guess) - .expect("Failed to read line"); + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); - let guess: u32 = guess.trim().parse().expect("Please type a number!"); + let guess: u32 = match guess.trim().to_lowercase().as_str() { + "one" => 1, + "two" => 2, + "three" => 3, + "four" => 4, + "five" => 5, + "six" => 6, + "seven" => 7, + "eight" => 8, + "nine" => 9, + "ten" => 10, + other => match other.parse() { + Ok(num) => num, + Err(_) => continue, + }, + }; - println!("You guessed: {guess}"); + println!("You guessed: {guess}"); - match guess.cmp(&secret_number) { - Ordering::Less => println!("Too small!"), - Ordering::Greater => println!("Too big!"), - Ordering::Equal => println!("You win!"), + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Equal => { + println!("You win!"); + break; + } + Ordering::Greater => println!("Too big!"), + } } }