search-algorithms/src/algorithm.cpp
2023-09-08 20:32:03 -05:00

53 lines
1.3 KiB
C++

#include "algorithm.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
Graph ReadInGraph(std::string fileLocation) {
std::cout << fileLocation << std::endl;
std::ifstream graphFile(fileLocation);
if (!graphFile.is_open()) {
std::cerr << "Error opening file, check filename" << std::endl;
exit(1);
}
Graph newGraph;
graphFile >> newGraph.nodeCount;
newGraph.nodes.resize(newGraph.nodeCount + 1);
std::string line;
int source, destination, weight;
while (std::getline(graphFile, line)) {
std::istringstream iss(line);
iss >> source;
do {
iss >> destination >> weight;
newGraph.AddChild(source, destination, weight);
} while (!iss.eof());
}
graphFile.close();
return newGraph;
}
Node::Node(int destination, int weight) {
this->destination = destination;
this->weight = weight;
}
Graph::Graph(void) {
nodeCount = -1;
}
void Graph::AddChild(int source, int destination, int weight) {
nodes.at(source).push_back(Node(destination, weight));
}
void Graph::PrintGraph(void) {
for (int i = 1; i < nodes.size(); i++) {
std::cout << "Source " << i << " ";
for (auto j : nodes.at(i)) { std::cout << "-> " << j.destination; }
std::cout << std::endl;
}
std::cout << std::endl;
}