Rust Challenge cont.

Continuing to learn rust via the python challenge. here is the solution to the next challenge…

extern crate regex;
extern crate reqwest;
#[macro_use]
extern crate error_chain;

error_chain! {
    foreign_links {
        ReqError(reqwest::Error);
        IoError(std::io::Error);
    }
}

fn nnothing(nothing:i32) -> String { 
    let req = format!("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing={}", nothing.to_string());
    let mut res = reqwest::get( &req ).expect("failed to contact server.");
    return res.text().expect("oops. it broke. no response.");
}


fn main() {
    let re = regex::Regex::new("next nothing is ([[:digit:]]+)").unwrap(); 
    let mut nn: i32 = 12345;
    let mut max: i32 = 420;
    while nn > 0 && max > 0 {
        max -= 1;
        let mut sub: String = "".to_string();
        let rtext = nnothing(nn);
        match re.captures(&rtext.as_str()) {
            Some(c) => sub=c.get(1).map_or("0", |m| m.as_str()).to_string(),
            None => nn = nn/2
        };
        println!("'{}'", rtext.as_str());
        match sub.parse::<i32>() {
            Ok(v) => nn = v,
            Err(m) => println!("{:#?}", m)
        }; 
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s