use std::{f32, fs::File, io::{BufRead, BufReader, Lines, Read}};
#[derive(Debug, Copy, Clone)]
pub struct TimeWindow {
pub earliest: usize,
pub latest : usize
}
impl TimeWindow {
pub fn new(earliest: usize, latest: usize) -> Self {
Self { earliest, latest }
}
}
#[derive(Clone)]
pub struct TsptwInstance {
pub nb_nodes : u16,
pub distances : Vec<Vec<usize>>,
pub timewindows: Vec<TimeWindow>
}
impl From<File> for TsptwInstance {
fn from(file: File) -> Self {
Self::from(BufReader::new(file))
}
}
impl <S: Read> From<BufReader<S>> for TsptwInstance {
fn from(buf: BufReader<S>) -> Self {
Self::from(buf.lines())
}
}
impl <B: BufRead> From<Lines<B>> for TsptwInstance {
fn from(lines: Lines<B>) -> Self {
let mut lc = 0;
let mut nb_nodes = 0_u16;
let mut distances = vec![];
let mut timewindows= vec![];
for line in lines {
let line = line.unwrap();
let line = line.trim();
if line.starts_with('#') || line.is_empty() {
continue;
}
if lc == 0 {
nb_nodes = line.split_whitespace().next().unwrap().to_string().parse::<u16>().unwrap();
distances = vec![vec![0; nb_nodes as usize]; nb_nodes as usize];
}
else if (1..=nb_nodes).contains(&lc) {
let i = (lc - 1) as usize;
for (j, distance) in line.split_whitespace().enumerate() {
let distance = distance.to_string().parse::<f32>().unwrap();
let distance = (distance * 10000.0) as usize;
distances[i][j] = distance;
}
}
else {
let mut tokens = line.split_whitespace();
let earliest = tokens.next().unwrap().to_string().parse::<f32>().unwrap();
let latest = tokens.next().unwrap().to_string().parse::<f32>().unwrap();
let earliest = (earliest * 10000.0) as usize;
let latest = (latest * 10000.0) as usize;
let timewindow = TimeWindow::new(earliest, latest);
timewindows.push(timewindow);
}
lc += 1;
}
TsptwInstance{nb_nodes, distances, timewindows}
}
}