use std::{num::ParseIntError, path::Path, fs::File, io::{BufReader, BufRead}};
#[derive(Debug, Clone)]
pub struct SrflpInstance {
pub nb_departments: usize,
pub lengths: Vec<isize>,
pub flows: Vec<Vec<isize>>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io error {0}")]
Io(#[from] std::io::Error),
#[error("parse int {0}")]
ParseInt(#[from] ParseIntError),
#[error("ill formed instance")]
Format,
}
pub fn read_instance<P: AsRef<Path>>(fname: P) -> Result<SrflpInstance, Error> {
let instance = String::from(fname.as_ref().to_str().unwrap());
let clearance = instance.contains("Cl");
let f = File::open(fname)?;
let f = BufReader::new(f);
let mut lines = f.lines();
let mut nb_departments = 0;
let mut lengths = vec![];
let mut flows = vec![];
let mut i = 0;
for line in &mut lines {
let line = line?;
if line.is_empty() {
continue;
}
let data = line.replace(',', " ");
let mut data = data.split_ascii_whitespace();
if i == 0 {
nb_departments = data.next().ok_or(Error::Format)?.parse()?;
} else if i == 1 {
for _ in 0..nb_departments {
lengths.push(data.next().ok_or(Error::Format)?.parse()?);
}
} else {
let mut f = vec![];for _ in 0..nb_departments {
f.push(data.next().ok_or(Error::Format)?.parse()?);
}
flows.push(f);
}
i += 1;
}
if clearance {
for item in lengths.iter_mut().take(nb_departments) {
*item += 10;
}
}
Ok(SrflpInstance { nb_departments, lengths, flows })
}