Skip to content

Instantly share code, notes, and snippets.

Created April 12, 2015 15:40
Show Gist options
  • Save anonymous/5d11942114dc0dcb3f8b to your computer and use it in GitHub Desktop.
Save anonymous/5d11942114dc0dcb3f8b to your computer and use it in GitHub Desktop.
extern crate regex;
use std::error::Error;
use std::io;
use std::io::prelude::*;
use std::process;
use regex::Regex;
type CliResult<T> = Result<T, Box<Error + Send>>;
fn main() {
if let Err(err) = run() {
writeln!(&mut io::stdout(), "{}", err).unwrap();
process::exit(1);
}
}
fn run() -> CliResult<()> {
let stdin = io::stdin();
let mut stdin = stdin.lock(); // gives us buffered access
let num_cases: i32 = try!(try!(read_line(&mut stdin)).trim().parse());
let re = Regex::new(r"^(?P<shy>[0-9]+)\s+(?P<digits>[0-9]+)\s*$").unwrap();
for i in 0..num_cases {
let line = try!(read_line(&mut stdin));
let caps = match re.captures(&line) {
Some(caps) => caps,
None => return Err(From::from(&*format!("Parse error: '{}'",
line))),
};
// The unwraps are OK because they are guaranteed to succeed if the
// regex matches.
let max_shyness: i32 = caps.name("shy").unwrap().parse().unwrap();
let str_digits: &str = caps.name("digits").unwrap();
let mut people_sum: u32 = 0;
let mut friends_required: u32 = 0;
let digits = str_digits.chars().map(|c| c.to_digit(10).unwrap());
for (i, digit) in digits.enumerate().map(|(i, d)| (i as u32, d)) {
if people_sum < i {
friends_required += i - people_sum;
people_sum += friends_required;
}
people_sum += digit;
}
println!("Case #{}: {}", i, friends_required);
}
Ok(())
}
fn read_line<R: BufRead>(mut rdr: R) -> io::Result<String> {
let mut buf = String::new();
let _ = try!(rdr.read_line(&mut buf));
Ok(buf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment