Anonymous user
Bulls and cows: Difference between revisions
→{{header|Rust}}: Updated to the Rust 1.2.0
m (→{{header|Julia}}: updated to julia v0.4) |
(→{{header|Rust}}: Updated to the Rust 1.2.0) |
||
Line 3,958:
=={{header|Rust}}==
<lang rust>use std::io;
use
extern crate rand;
static NUMBER_OF_DIGITS: uint = 4;▼
static DIGITS: [char, ..9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];▼
fn generate_digits() -> Vec<char> {
let mut temp_digits: Vec<_> =
return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect();
}
fn parse_guess_string(guess: &
let chars: Vec<char> =
if !chars.iter().all(|c| DIGITS.contains(c)) {
return Err("only digits, please".to_string());
}
if chars.len() != NUMBER_OF_DIGITS {
return Err(format!("you need to guess with {
let mut uniques: Vec<char> = chars.clone();
uniques.dedup();
if uniques.len() != chars.len() {
return Err("no duplicates, please".to_string());
}
return Ok(chars);
}
fn calculate_score(given_digits: &
let mut bulls = 0;
let mut cows = 0;
for i in
let pos: Option<
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1
}▼
}
return (bulls, cows);▼
▲ return (bulls, cows);
}
fn main() {
loop {▼
let given_digits = generate_digits();▼
println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS);▼
loop {
▲ let given_digits = generate_digits();
▲ println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS);
▲ loop {
let guess_string: String = {
let mut buf = String::new();
reader.read_line(&mut buf).unwrap();
buf.trim().into()
};
let digits_maybe = parse_guess_string(&guess_string);
match digits_maybe {
Err(msg) => {
println!("{}", msg);
continue;
},
Ok(guess_digits) => {
match calculate_score(&given_digits, &guess_digits) {
(NUMBER_OF_DIGITS, _) => {
println!("you win!");
break;
},
(bulls, cows) => println!("bulls: {
}
}
}
}
▲ }
}
}</lang>
|