-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImproved.cpp
More file actions
615 lines (523 loc) · 22.5 KB
/
Improved.cpp
File metadata and controls
615 lines (523 loc) · 22.5 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#include<bits/stdc++.h>
using namespace std;
const string DATA_FILE = "campus_data.txt";
const string BACKUP_FILE = "campus_backup.txt";
const string ADMIN_FILE = "admin.txt";
int getValidInt(const string& prompt) {
int value;
while (true) {
cout << prompt;
if (cin >> value) {
break;
} else {
cout << "Invalid input. Please enter a valid number.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
return value;
}
double getValidDouble(const string& prompt) {
double value;
while (true) {
cout << prompt;
if (cin >> value) {
break;
} else {
cout << "Invalid input. Please enter a valid number.\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
return value;
}
// Location class -> Informations of every Location
class Location {
public:
int id;
string name;
int importance; // 1 - 10
int cleaningFrequency; // Preffered Days between cleanings
int visitPriority; // Base priority 1-10
int lastCleaned; // Days since last cleaned
double cleanlinessStatus; // 0-100%
double cleaningCost;
Location(int id, string name, int importance, int cleaningFrequency,
int visitPriority, double cleanlinessStatus, double cleaningCost = 10.0)
: id(id), name(name), importance(importance), cleaningFrequency(cleaningFrequency),
visitPriority(visitPriority), lastCleaned(0), cleanlinessStatus(cleanlinessStatus), cleaningCost(cleaningCost) {}
};
// Path class -> representing connections between locations
class Path {
public:
int from, to;
double distance;
double travelTime;
double difficulty; // Factor representing road condition
Path(int from, int to, double distance, double travelTime = 1.0, double difficulty = 1.0)
: from(from), to(to), distance(distance), travelTime(travelTime), difficulty(difficulty) {}
};
// CampusMap class -> manage locations and paths
class CampusMap {
private:
vector<Location> locations;
vector<vector<Path>> adjacencyList;
unordered_map<int, int> visitCounts;
public:
CampusMap() {}
void addLocation(Location loc) {
locations.push_back(loc);
visitCounts[loc.id] = 0;
}
void addPath(Path p) { adjacencyList[p.from].push_back(p); }
Location* getLocationById(int id) {
for (auto &loc : locations) {
if (loc.id == id) {
return &loc;
}
}
return nullptr;
}
Location* getLocationByName(const string& name) {
for (auto &loc : locations) {
if (loc.name == name) {
return &loc;
}
}
return nullptr;
}
void updateCleanlinessStatus(int days) {
for (auto &loc : locations) {
loc.lastCleaned += days;
// Cleanliness decreases over time
double decayRate = 100.0 / (loc.cleaningFrequency * 2); // % loss per day
loc.cleanlinessStatus = max(0.0, loc.cleanlinessStatus - (days * decayRate));
}
}
void cleanLocation(int locId) {
for (auto &loc : locations) {
if (loc.id == locId) {
loc.lastCleaned = 0;
loc.cleanlinessStatus = 100.0;
visitCounts[locId]++;
break;
}
}
}
double calculateDynamicPriority(int locId) {
for (const auto &loc : locations) {
if (loc.id == locId) {
// Calculate priority based on multiple factors
double timeFactorNormalized = min(1.0, static_cast<double>(loc.lastCleaned) / loc.cleaningFrequency);
if (loc.lastCleaned < loc.cleaningFrequency) timeFactorNormalized *= 0.2; // Penalize recently cleaned locations
double normImportance = loc.importance;
double normCleanliness = (100.0 - loc.cleanlinessStatus) / 10.0;
double normVisitPriority = loc.visitPriority;
double normTimeFactor = timeFactorNormalized * 10.0;
double priority = (normImportance * 0.3) +
(normCleanliness * 0.4) +
(normVisitPriority * 0.1) +
(normTimeFactor * 0.2);
return priority;
}
}
return 0.0;
}
const vector<vector<Path>>& getAdjacencyList() const {
return adjacencyList;
}
const vector<Location>& getLocations() const {
return locations;
}
int getVisitCount(int locId) const {
if (visitCounts.find(locId) != visitCounts.end()) {
return visitCounts.at(locId);
}
return 0;
}
void printLocationsStatus() const {
cout << "\n=== Campus Locations Status ===\n";
cout << setw(30) << left << "Location"
<< setw(14) << right << "Cleanliness"
<< setw(16) << right << "Last Cleaned"
<< setw(14) << right << "Priority"
<< setw(13) << right << "Visits\n";
cout << string(87, '-') << "\n";
for (const auto &loc : locations) {
double priority = const_cast<CampusMap*>(this)->calculateDynamicPriority(loc.id);
cout << setw(30) << left << loc.name
<< setw(9) << right << fixed << setprecision(2) << loc.cleanlinessStatus << " %"
<< setw(13) << right << loc.lastCleaned << " days"
<< setw(14) << right << fixed << setprecision(2) << priority
<< setw(10) << right << visitCounts.at(loc.id) << "\n";
}
cout << "\n";
}
// New file handling methods
bool saveToFile(const string& filename) {
ofstream outFile(filename);
if (!outFile) {
cerr << "Error opening file for writing: " << filename << endl;
return false;
}
// Save locations
outFile << "# Locations\n";
for (const auto& loc : locations) {
outFile << loc.id << ","
<< loc.name << ","
<< loc.importance << ","
<< loc.cleaningFrequency << ","
<< loc.visitPriority << ","
<< loc.cleanlinessStatus << ","
<< loc.lastCleaned << ","
<< visitCounts[loc.id] << ","
<< loc.cleaningCost << "\n";
}
// Save paths
outFile << "# Paths\n";
for (int from = 0; from < adjacencyList.size(); ++from) {
for (const auto& path : adjacencyList[from]) {
outFile << path.from << ","
<< path.to << ","
<< path.distance << ","
<< path.travelTime << ","
<< path.difficulty << "\n";
}
}
outFile.close();
return true;
}
bool loadFromFile(const string& filename) {
ifstream inFile(filename);
if (!inFile) {
cerr << "Data file not found. Starting with new data.\n";
return false;
}
locations.clear();
visitCounts.clear();
adjacencyList.clear();
string line;
string currentSection;
while (getline(inFile, line)) {
if (line.empty()) continue;
// Check section headers
if (line == "# Locations" || line == "# Paths") {
currentSection = line;
continue;
}
stringstream ss(line);
string token;
vector<string> tokens;
while (getline(ss, token, ',')) tokens.push_back(token);
try {
// Process locations
if (currentSection == "# Locations" && tokens.size() >= 8) {
double cleaningCost = (tokens.size() >= 9) ? stod(tokens[8]) : 10.0;
Location loc(stoi(tokens[0]), tokens[1], stoi(tokens[2]),
stoi(tokens[3]), stoi(tokens[4]), stod(tokens[5]), cleaningCost);
loc.lastCleaned = stoi(tokens[6]);
locations.push_back(loc);
visitCounts[loc.id] = stoi(tokens[7]);
}
// Process paths
else if (currentSection == "# Paths" && tokens.size() == 5) {
int from = stoi(tokens[0]);
Path p(from, stoi(tokens[1]), stod(tokens[2]),
stod(tokens[3]), stod(tokens[4]));
if (from >= adjacencyList.size()) adjacencyList.resize(from + 1);
adjacencyList[from].push_back(p);
}
else cerr << "Invalid format in " << currentSection << ": " << line << endl;
}
catch (const exception& e) { cerr << "Error parsing line: " << e.what() << endl; }
}
inFile.close();
return true;
}
};
class ModifiedDijkstra {
private:
CampusMap* campus;
double alpha, beta, gamma, delta; // Weight factors
public:
ModifiedDijkstra(CampusMap* c, double a = 0.6, double b = 0.3, double g = 0.1, double d = 0.2)
: campus(c), alpha(a), beta(b), gamma(g), delta(d) {}
pair<vector<int>,double> findPath(int start, int end) {
const auto& adjList = campus->getAdjacencyList();
int n = adjList.size();
vector<double> distances(n, INT_MAX);
vector<int> parents(n, -1);
distances[start] = 0;
priority_queue<pair<double, int>, vector<pair<double, int>>, greater<>> pq;
pq.push({0, start});
while (!pq.empty()) {
double cost = pq.top().first;
int node = pq.top().second;
pq.pop();
if (cost > distances[node]) continue;
for (const auto& edge : adjList[node]) {
int to = edge.to;
// Calculate weighted edge cost
double priorityFactor = 1.0 - (campus->calculateDynamicPriority(to) / 100.0);
double visitFactor = 1.0 + (campus->getVisitCount(to) * delta);
double weight = (alpha * edge.distance) +
(beta * edge.difficulty) +
(gamma * visitFactor);
// Priority reduces the cost (more important locations are easier to include)
weight *= (2.0 - priorityFactor);
double newCost = distances[node] + weight;
if (newCost < distances[to]) {
distances[to] = newCost;
parents[to] = node;
pq.push({newCost, to});
}
}
}
vector<int> path;
if (distances[end] == INT_MAX) {
// No path exists
return {path,distances[end]};
}
for (int at = end; at != -1; at = parents[at]) {
path.push_back(at);
}
reverse(path.begin(), path.end());
return {path,distances[end]};
}
};
// Maintenance Scheduler for generating daily routes
class MaintenanceScheduler {
private:
CampusMap* campus;
ModifiedDijkstra* pathFinder;
public:
MaintenanceScheduler(CampusMap* c, ModifiedDijkstra* d)
: campus(c), pathFinder(d) {}
pair<vector<int>,double> generateDailyRoutes(int startLocation, double cleanlinessThreshold = 100.0, std::unordered_set<int>* outCleaned = nullptr) {
// Get locations-priority for today
vector<pair<int, double>> priorityList;
const auto& locations = campus->getLocations();
for (const auto& loc : locations) {
if (loc.cleanlinessStatus <= cleanlinessThreshold && loc.id != startLocation) {
double priority = campus->calculateDynamicPriority(loc.id);
priorityList.push_back({loc.id, priority});
}
}
// Sort by priority (descending)
sort(priorityList.begin(), priorityList.end(),
[](const pair<int, double>& a, const pair<int, double>& b) {
return a.second > b.second;
});
// Take top priorities (about 1/3 of locations each day)
int locationsToVisit = max(1, static_cast<int>(locations.size() / 3));
vector<int> priorityLocations;
for (int i = 0; i < min(locationsToVisit, static_cast<int>(priorityList.size())); i++) {
priorityLocations.push_back(priorityList[i].first);
}
// Plan route to visit these locations
pair<vector<int>,double> routeAndcost = planRoute(startLocation, priorityLocations);
vector<int> route = routeAndcost.first;
double cost = routeAndcost.second;
// Mark visited locations as cleaned
for (int loc : route) {
Location* location = campus->getLocationById(loc);
if (location && location->cleanlinessStatus <= cleanlinessThreshold) {
campus->cleanLocation(loc);
cost += location->cleaningCost;
if (outCleaned) outCleaned->insert(loc);
}
}
return {route,cost};
}
private:
// Helper function to plan a route visiting all specified destinations
pair<vector<int>,double> planRoute(int start, vector<int> destinations) {
vector<int> route = {start};
int currentLocation = start;
double totalCost = 0;
// Simple greedy approach: visit nearest unvisited high-priority location
while (!destinations.empty()) {
double bestDist = INT_MAX;
int bestDest = -1;
int bestIndex = -1;
for (int i = 0; i < destinations.size(); i++) {
pair<vector<int>,double> path_cost = pathFinder->findPath(currentLocation, destinations[i]);
vector<int> path = path_cost.first;
double cost = path_cost.second;
if (!path.empty() && path.size() > 1) { // Valid path exists
double distance = path.size() - 1; // Simple distance measure
if (distance < bestDist) {
bestDist = distance;
bestDest = destinations[i];
bestIndex = i;
}
}
}
if (bestDest == -1) {
// No reachable destination
break;
}
// Get the path to the best destination
pair<vector<int>,double> path_cost = pathFinder->findPath(currentLocation, bestDest);
vector<int> path = path_cost.first;
double cost = path_cost.second;
totalCost += cost;
// Add all intermediate nodes to the route (excluding the first, which is current location)
for (int i = 1; i < path.size(); i++) {
route.push_back(path[i]);
}
// Update current location
currentLocation = bestDest;
// Remove the visited destination
destinations.erase(destinations.begin() + bestIndex);
}
return {route,totalCost};
}
};
// Utility functions for simulation
void displayPath(const vector<int>& path, CampusMap* campus, bool showAction = false, const std::unordered_set<int>& actuallyCleaned = {}) {
if (path.empty()) {
cout << "No path found!\n";
return;
}
cout << "Path: ";
unordered_set<int> cleanedThisRoute;
for (int i = 0; i < path.size(); i++) {
Location* loc = campus->getLocationById(path[i]);
if (loc) {
cout << loc->name;
if (showAction) {
if (actuallyCleaned.find(loc->id) != actuallyCleaned.end() && cleanedThisRoute.find(path[i]) == cleanedThisRoute.end()) {
cout << " (Cleaned)";
cleanedThisRoute.insert(path[i]);
} else {
cout << " (Passed)";
}
}
if (i < path.size() - 1) {
cout << " -> ";
}
}
}
cout << "\n";
}
void runSimulation(CampusMap* campus, ModifiedDijkstra* pathFinder, int days, int startLocation, double cleanlinessThreshold) {
MaintenanceScheduler scheduler(campus, pathFinder);
cout << "\n=== Starting Campus Maintenance Simulation for " << days << " days ===\n";
campus->printLocationsStatus();
for (int day = 0; day < days; day++) {
cout << "\n=== Day " << (day + 1) << " ===\n";
cout << "--- Morning Status (Before Cleaning) ---";
campus->printLocationsStatus();
std::unordered_set<int> cleanedToday;
pair<vector<int>,double> schedulesAndcost = scheduler.generateDailyRoutes(startLocation, cleanlinessThreshold, &cleanedToday);
vector<int> schedules = schedulesAndcost.first;
double cost = schedulesAndcost.second;
displayPath(schedules, campus, true, cleanedToday);
cout<<"Route Cost -> "<<cost<<'\n';
cout << "--- Evening Status (After Cleaning) ---";
campus->printLocationsStatus();
campus->updateCleanlinessStatus(1);
}
}
int main() {
CampusMap campus;
bool loaded = campus.loadFromFile(BACKUP_FILE);
if(!loaded){
cout<<"Has no backup file. Reseting the campus map."<<endl;
campus.loadFromFile(DATA_FILE);
}
int numLocations = campus.getAdjacencyList().size();
ModifiedDijkstra pathFinder(&campus);
bool running = true;
while (running) {
cout << "\nOptions:\n";
cout << "1. Find optimal path between two locations\n";
cout << "2. View campus status\n";
cout << "3. Run simulation for multiple days\n";
cout << "4. Reset to default configuration\n";
cout << "5. Exit\n";
int choice = getValidInt("Enter your choice: ");
switch (choice) {
case 1: {
cout << "\nAvailable locations:\n";
const auto& locations = campus.getLocations();
for (const auto& loc : locations) {
cout << loc.id << ": " << loc.name << "\n";
}
int sourceId = getValidInt("Enter source location ID: ");
int destId = getValidInt("Enter destination location ID: ");
if (sourceId < 0 || sourceId >= numLocations || destId < 0 || destId >= numLocations) {
cout << "Invalid location ID(s). Please try again.\n";
break;
}
pair<vector<int>,double> path_cost = pathFinder.findPath(sourceId, destId);
vector<int> path = path_cost.first;
double cost = path_cost.second;
cout << "\nOptimal path found: \n";
displayPath(path, &campus);
cout<<"Cost -> "<<cost<<'\n';
break;
}
case 2:
campus.printLocationsStatus();
break;
case 3: {
int days = getValidInt("Enter number of days to simulate: ");
if (days <= 0 || days > 30) {
cout << "Invalid number of days. Please enter a value between 1 and 30.\n";
break;
}
cout << "\nAvailable locations:\n";
const auto& locations = campus.getLocations();
for (const auto& loc : locations) {
cout << loc.id << ": " << loc.name << "\n";
}
int startLocation = getValidInt("Enter starting location ID: ");
double cleanlinessThreshold = getValidDouble("Enter cleanliness threshold (e.g. 100 for all, 95 to skip clean places): ");
runSimulation(&campus, &pathFinder, days, startLocation, cleanlinessThreshold);
campus.saveToFile(BACKUP_FILE); // Auto-save after simulation
break;
}
case 4: {
string password = "";
cout<<"Enter password : ";
cin>>password;
ifstream inFile(ADMIN_FILE);
string admin_password = "admin";
if (inFile) {
getline(inFile,admin_password);
inFile.close();
}
if(password != admin_password){
cout<<"Invalid Password. Exiting.\n";
inFile.close();
break;
}
inFile.close();
cout<<"Resetting to default configuration.\n";
// Copy the Default Campus data to Backup data
ifstream source(DATA_FILE, ios::binary);
ofstream dest(BACKUP_FILE, ios::binary);
if (!source || !dest) {
cerr << "Error opening files!" << endl;
return 0;
}
dest << source.rdbuf();
source.close();
dest.close();
campus.loadFromFile(BACKUP_FILE);
break;
}
case 5:
campus.saveToFile(BACKUP_FILE);
cout<<"All data is saved. Existing Programme.\n";
running = false;
break;
default:
cout << "Invalid choice. Please try again.\n";
break;
}
}
return 0;
}