Skip to content
This repository has been archived by the owner on Mar 7, 2024. It is now read-only.

Week1 exercise #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 39 additions & 13 deletions week1/src/main.rs
Original file line number Diff line number Diff line change
@@ -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,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

},
};

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!"),
}
}
}