Added graph input

This commit is contained in:
TriantaTV 2023-09-08 20:32:03 -05:00
parent 32f3d672e5
commit e4016b54e6
4 changed files with 84 additions and 2 deletions

View File

@ -1,5 +1,6 @@
add_executable(search-algorithms add_executable(search-algorithms
./main.cpp ./main.cpp
./algorithm.cpp
) )
target_include_directories(search-algorithms PUBLIC ${CMAKE_CURRENT_LIST_DIR}) target_include_directories(search-algorithms PUBLIC ${CMAKE_CURRENT_LIST_DIR})

52
src/algorithm.cpp Normal file
View File

@ -0,0 +1,52 @@
#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;
}

23
src/algorithm.hpp Normal file
View File

@ -0,0 +1,23 @@
#ifndef ALGORITHM_HPP
#define ALGORITHM_HPP
#include <string>
#include <vector>
struct Node {
int destination;
int weight;
Node(int destination, int weight);
};
struct Graph {
int nodeCount;
std::vector<std::vector<Node>> nodes;
Graph(void);
void AddChild(int source, int destination, int weight);
void PrintGraph(void);
};
Graph ReadInGraph(std::string fileLocation);
#endif

View File

@ -1,6 +1,12 @@
#include "algorithm.hpp"
#include <iostream> #include <iostream>
int main () { int main(int argc, char* argv[]) {
std::cout << "Hello world" << std::endl; if (argc != 2) {
std::cerr << "Usage: search-algorithms graphFile.txt" << std::endl;
return 1;
}
Graph newGraph = ReadInGraph(argv[1]);
newGraph.PrintGraph();
return 0; return 0;
} }