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}}==
{{works with|Rust|0.12.0-pre-nightly}}
<lang rust>use std::io;
use std::rand::{task_rngRng, Rngthread_rng};
 
extern crate rand;
static NUMBER_OF_DIGITS: uint = 4;
 
staticconst NUMBER_OF_DIGITS: uintusize = 4;
static DIGITS: [char, ..9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
 
static DIGITS: [char,; ..9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
 
fn generate_digits() -> Vec<char> {
let mut temp_digits: Vec<_> = Vec::from_slice(&DIGITS[..]).into();
task_rng thread_rng().shuffle(&mut temp_digits.as_mut_slice());
return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect();
}
 
fn parse_guess_string(guess: &Stringstr) -> Result<Vec<char>, String> {
let chars: Vec<char> = guess.as_slice(&guess).chars().collect();
 
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 {:u} digits", NUMBER_OF_DIGITS));
} }
 
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: &Vec<[char>], guessed_digits: &Vec<[char>]) -> (uintusize, uintusize) {
let mut bulls = 0;
let mut cows = 0;
for i in range(0, ..NUMBER_OF_DIGITS) {
let pos: Option<uintusize> = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]});
match match pos {
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1
}
}
return (bulls, cows);
}
return (bulls, cows);
}
 
fn main() {
let mut let reader = io::stdin();
 
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);
let guess_string = reader.read_line().unwrap().as_slice().trim().to_string();
 
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: {:u}, cows: {:u}", bulls, cows)
}
}
}
}
}
}
}
}</lang>