Created
September 16, 2022 11:02
-
-
Save 1010real/beca69993d58a5916e29d69fc3963afc to your computer and use it in GitHub Desktop.
first try rust - number 5 game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::{io, cmp::Ordering, convert::TryInto}; | |
use rand::Rng; | |
fn main() { | |
println!("Guess the number!"); | |
let secret_numbers:[u32; 5] = [ | |
rand::thread_rng().gen_range(0..10), | |
rand::thread_rng().gen_range(0..10), | |
rand::thread_rng().gen_range(0..10), | |
rand::thread_rng().gen_range(0..10), | |
rand::thread_rng().gen_range(0..10), | |
]; | |
let secret_numbers_string = secret_numbers.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", "); | |
println!("The secret number is: {}", secret_numbers_string); | |
loop { | |
println!("Please input your guess."); | |
let mut guess = String::new(); | |
io::stdin() | |
.read_line(&mut guess) | |
.expect("Failed to read line"); | |
let guesses: [u32; 5] = guess.trim().chars().map(|x| x.to_digit(10).unwrap()).collect::<Vec<u32>>().try_into().unwrap(); | |
println!("You guessed: {}", guesses.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", ")); | |
let mut correct_guesses: u32 = 0; | |
// use index only version | |
// for i in 0..5 { | |
// match guesses[i].cmp(&secret_numbers[i]) { | |
// Ordering::Less => println!("Too small!"), | |
// Ordering::Greater => println!("Too big!"), | |
// Ordering::Equal => { | |
// println!("{} is equal!", guesses[i]); | |
// correct_guesses += 1; | |
// } | |
// } | |
// } | |
// use iterator version | |
// let mut i: usize = 0; | |
// for g in guesses.iter() { | |
// match g.cmp(&secret_numbers[i]) { | |
// Ordering::Less => println!("{} is too small!", g), | |
// Ordering::Greater => println!("{} is too big!", g), | |
// Ordering::Equal => { | |
// println!("{} is equal!", g); | |
// correct_guesses += 1; | |
// }, | |
// } | |
// i += 1; | |
// } | |
// use iterator with index version | |
for (i, g) in guesses.iter().enumerate() { | |
match g.cmp(&secret_numbers[i]) { | |
Ordering::Less => println!("{} is too small!", g), | |
Ordering::Greater => println!("{} is too big!", g), | |
Ordering::Equal => { | |
println!("{} is equal!", g); | |
correct_guesses += 1; | |
}, | |
} | |
} | |
if correct_guesses == 5 { | |
println!("You win!"); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment