-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileHandler.cpp
More file actions
128 lines (90 loc) · 2.47 KB
/
FileHandler.cpp
File metadata and controls
128 lines (90 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "FileHandler.h"
#include <fstream>
#include <sstream>
#include <vector>
#include <iostream>
#include <string>
Graph* FileHandler::load_graph(string path) {
ifstream dataFile(path);
if (!dataFile.is_open()) {
throw std::runtime_error("error: File not found.");
}
string line = "";
Graph* data = nullptr;
int i = 0;
int no_vertices = 0;
getline(dataFile, line);
getline(dataFile, line);
getline(dataFile, line);
getline(dataFile, line);
line.erase(0, 11);
no_vertices = stoi(line);
getline(dataFile, line);
getline(dataFile, line);
getline(dataFile, line);
data = new Graph(no_vertices);
int** matrix = new int* [no_vertices];
for (int i = 0; i < no_vertices; i++) {
matrix[i] = new int[no_vertices];
}
for (int i = 0; i < no_vertices; i++) {
for (int j = 0; j < no_vertices; j++) {
dataFile >> matrix[i][j];
}
}
data->data = matrix;
return data;
}
int FileHandler::load_solution(Graph* data, string path) {
ifstream dataFile(path);
if (!dataFile.is_open()) {
throw std::runtime_error("error: File not found.");
}
string line;
getline(dataFile, line);
int no_vertices = stoi(line);
if (no_vertices + 1 != data->no_vertices) {
cout << endl << "the saved solution appears to be generated for different graph" << endl;
return -1;
}
vector<int> solution;
getline(dataFile, line);
stringstream ss(line);
int vertex;
while (ss >> vertex) {
solution.push_back(vertex);
}
dataFile.close();
int cost = 0;
for (int i = 0; i < solution.size() - 1; i++) {
cost += data->edge_weight(solution[i], solution[i + 1]);
}
return cost;
}
void FileHandler::save_records(vector<pair<int, double>> records, string path) {
ofstream file(path);
if (!file.is_open()) {
throw ios_base::failure("Failed to open the file: " + path);
}
for (size_t i = 0; i < records.size(); ++i) {
file << to_string(records[i].first) + ";" + to_string(records[i].second) + '\n';
}
file.close();
}
void FileHandler::save_solution(vector<int> solution, string path) {
ofstream file(path);
if (!file.is_open()) {
throw ios_base::failure("Failed to open the file: " + path);
}
file << solution.size() << "\n";
for (size_t i = 0; i < solution.size(); ++i) {
file << solution[i];
if (i < solution.size() - 1) {
file << " ";
}
}
file << " " << solution[0];
file << "\n";
file.close();
cout << "file saved" << endl;
}