OptimisationProblem/structures/Distances.cpp

55 lines
1.3 KiB
C++
Raw Permalink Normal View History

2023-07-17 00:19:10 +02:00
#include "Distances.h"
Distances::Distances(std::string basePath)
{
std::string filePath = basePath + "/distances.csv";
if (!std::filesystem::exists(filePath.c_str()))
throw std::runtime_error("File doesn't exist");
std::cout << "Reading file " << filePath << " for distances\n";
std::ifstream file;
file.open(filePath, std::ios::in);
if (!file.is_open())
throw std::runtime_error("Failed to open file");
std::string line;
while (getline(file, line)) {
if (line.empty())
continue;
std::string element;
std::istringstream stream(line);
std::vector<float> row;
while (getline(stream, element, ',')) {
int val = stoi(element);
row.push_back(val);
}
this->matrix.push_back(row);
}
file.close();
if (this->matrix.size() == 0)
throw std::runtime_error("File contained no data");
}
float Distances::getDistance(int x, int y)
{
int xMax = this->matrix.size() - 1;
int yMax = this->matrix[0].size() - 1;
if (yMax == 0)
throw std::runtime_error("Distances not initialised properly");
else if (x < 1 || x > xMax)
throw std::domain_error("X coordiante must be between 1 and " + xMax);
else if (y < 1 || y > yMax)
throw std::domain_error("Y coordinate must be between 1 and " + yMax);
return this->matrix[x - 1][y - 1];
}
float Distances::getTravelTime(int x, int y)
{
return this->getDistance(x, y) / 55 * 60;
}