Add a (pseudo) random number

Right now the secret number is neither secret nor random. If we were not using Repl.it, we could do this:

extern crate rand;
use rand::Rng;

let secret_number = rand::thread_rng().gen_range(1, 101);

But Repl.it does not allow us to use external crates! So let's find a workaround using time and math:

use std::time::{SystemTime, UNIX_EPOCH};

let nanos = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .unwrap()
    .subsec_nanos();

let secret_number = nanos / 13000000;

It's not perfect, but it'll get us a pseudorandom number that will generally be between 1 and 100. One last thing: right now, we are printing our secret number! Where's the fun in that? Let's remove that line and now our guessing game is complete:

main.rs
use std::io;
use std::cmp::Ordering;
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    println!("Guess the number!");
    
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .subsec_nanos();

    let secret_number = nanos / 13000000;

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
              Ok(num) => num,
              Err(msg) => {
                println!("{}", msg);
                continue;
              },
          };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
              println!("You win!");
              break;
            },
        }
    }
}

Last updated