100-days-of-rust/Week-07/Day-49_Swimming-Pool/day49/src/main.rs

61 lines
1.5 KiB
Rust

use std::io;
use std::process::exit;
use day49::is_legitimate;
fn read_row() -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut buffer = String::new();
io::stdin().read_line(&mut buffer)?;
let row: Vec<u8> = buffer
.split_whitespace()
.map(|x: &str| match x.parse::<u8>() {
Ok(x) => match x {
0 | 1 => Ok(x),
_ => Err("Only 0 and 1 are accepted".to_string()),
},
Err(_) => Err("Only numbers are accepted".to_string()),
})
.collect::<Result<Vec<u8>, String>>()?;
if row.is_empty() {
Err("Empty row")?
}
Ok(row)
}
fn read_pool() -> Result<Vec<Vec<u8>>, Box<dyn std::error::Error>> {
let mut pool = vec![read_row()?];
while let Ok(row) = read_row() {
if row.len() != pool.first().unwrap().len() {
Err("Invalid row length")?
}
pool.push(row);
}
Ok(pool)
}
fn main() {
println!("Insert the pool (space-separated 0s and 1s, one row per line)");
println!("End input with an empty line");
let pool = match read_pool() {
Ok(x) => x,
Err(e) => {
eprintln!("Error: {e}");
exit(1);
}
};
if let Some(legit) = is_legitimate(&pool) {
if legit {
println!("The pool is legitimate");
} else {
println!("The pool is not legitimate");
}
} else {
println!("Invalid pool");
}
}