-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
599 lines (538 loc) · 30.7 KB
/
Copy pathmain.cpp
File metadata and controls
599 lines (538 loc) · 30.7 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
// main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector> // Needed for parts vector, path, pickupNodes
#include <unordered_map> // Needed for cityHubs map
#include <limits> // For infinity check and input clearing
#include <stdexcept> // For stod exceptions
#include <set> // For getting unique lists from Graph
#include <algorithm> // Needed for std::transform, std::find, std::tolower
#include <iterator> // Needed for std::inserter
#include <iomanip> // Needed for std::setprecision, std::fixed
#include "Graph.h" // Include our Graph class definition
// --- Helper Function to load INTRA-CITY data ---
void loadIntraCityData(Graph& graph, const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error: Could not open file " << filename << std::endl;
return;
}
std::string line;
int lineNumber = 0;
while (std::getline(file, line)) {
lineNumber++;
// Skip empty lines or lines starting with '#' (comments) or lines with only whitespace
if (line.empty() || line.find_first_not_of(" \t\r\n") == std::string::npos || line[0] == '#') {
continue;
}
std::stringstream ss(line);
std::string segment;
std::vector<std::string> parts;
while (std::getline(ss, segment, ',')) {
// Trim leading/trailing whitespace from segment
size_t first = segment.find_first_not_of(" \t\r\n");
if (std::string::npos == first) { // Handle segments that are purely whitespace
parts.push_back(""); // Add empty string if segment was just whitespace
continue;
}
size_t last = segment.find_last_not_of(" \t\r\n");
parts.push_back(segment.substr(first, (last - first + 1)));
}
if (parts.size() == 5) {
std::string state = parts[0];
std::string city = parts[1];
std::string loc1_name = parts[2];
std::string loc2_name = parts[3];
try {
// Check if any crucial part is empty
if (state.empty() || city.empty() || loc1_name.empty() || loc2_name.empty() || parts[4].empty()) {
std::cerr << "Error: Empty field(s) in line " << lineNumber << " of " << filename << ": " << line << std::endl;
continue; // Skip this line
}
double distance = std::stod(parts[4]);
// Ensure distance is non-negative
if (distance < 0) {
std::cerr << "Error: Negative distance in line " << lineNumber << " of " << filename << ": " << line << std::endl;
continue;
}
std::string uniqueLoc1 = state + "," + city + "," + loc1_name;
std::string uniqueLoc2 = state + "," + city + "," + loc2_name;
graph.addEdge(uniqueLoc1, uniqueLoc2, distance);
} catch (const std::invalid_argument& ia) {
std::cerr << "Error converting distance to double in line " << lineNumber << " of " << filename << ": " << line << " (" << ia.what() << ")" << std::endl;
} catch (const std::out_of_range& oor) {
std::cerr << "Distance value out of range in line " << lineNumber << " of " << filename << ": " << line << " (" << oor.what() << ")" << std::endl;
}
} else {
std::cerr << "Warning: Skipping malformed line " << lineNumber << " in " << filename << " (expected 5 columns, found " << parts.size() << "): " << line << std::endl;
}
}
file.close();
std::cout << "Successfully processed " << filename << std::endl;
}
// --- Helper Function to load INTER-CITY data ---
void loadInterCityData(Graph& graph, const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error: Could not open file " << filename << std::endl;
return;
}
std::string line;
int lineNumber = 0;
// Define the cityHubs map - maps City Name to its main Hub Location Name
std::unordered_map<std::string, std::string> cityHubs = {
{"Ambala", "Bus Stand (Cantt)"},{"Karnal", "Bus Stand (ISBT)"},{"Panchkula", "ISBT Sector 5"},
{"Yamunanagar", "Bus Stand"},{"Kaithal", "Bus Stand"},{"Bhiwani", "Bus Stand"},
{"Hisar", "Bus Stand"},{"Rohtak", "Bus Stand (New)"},{"Rewari", "Bus Stand"},
{"Faridabad", "NIT Bus Stand"},{"Sonipat", "Bus Stand"},{"Gurugram", "Bus Stand"},
{"Fatehabad", "Bus Stand"},{"Jind", "Bus Stand"},{"Sirsa", "Bus Stand"},
{"Panipat", "Bus Stand"},{"Amritsar", "Bus Stand (ISBT)"},{"Jalandhar", "Bus Stand (ISBT)"},
{"Ludhiana", "Bus Stand (ISBT)"},{"Pathankot", "Bus Stand"},{"Gurdaspur", "Bus Stand"},
{"Hoshiarpur", "Bus Stand"},{"Firozpur", "Bus Stand"},{"Bathinda", "Bus Stand"},
{"Moga", "Bus Stand"},{"Mansa", "Bus Stand"},{"Patiala", "Bus Stand (New)"},
{"Khanna", "Bus Stand"},{"Malerkotla", "Bus Stand"},{"Kapurthala", "Bus Stand"},
{"Mohali", "ISBT Mohali (Phase 8)"},{"Chandigarh", "ISBT Sector 17"},
{"Abohar (Fazilka Dist.)", "Bus Stand"}
};
while (std::getline(file, line)) {
lineNumber++;
if (line.empty() || line.find_first_not_of(" \t\r\n") == std::string::npos || line[0] == '#') {
continue;
}
std::stringstream ss(line);
std::string segment;
std::vector<std::string> parts;
while (std::getline(ss, segment, ',')) {
size_t first = segment.find_first_not_of(" \t\r\n");
if (std::string::npos == first) { parts.push_back(""); continue; }
size_t last = segment.find_last_not_of(" \t\r\n");
parts.push_back(segment.substr(first, (last - first + 1)));
}
if (parts.size() == 4) {
std::string state = parts[0];
std::string city1 = parts[1];
std::string city2 = parts[2];
try {
if (state.empty() || city1.empty() || city2.empty() || parts[3].empty()) {
std::cerr << "Error: Empty field(s) in line " << lineNumber << " of " << filename << ": " << line << std::endl;
continue;
}
double distance = std::stod(parts[3]);
if (distance < 0) {
std::cerr << "Error: Negative distance in line " << lineNumber << " of " << filename << ": " << line << std::endl;
continue;
}
if (cityHubs.count(city1) && cityHubs.count(city2)) {
// Create full node names like "Haryana,Rohtak,Bus Stand (New)"
std::string uniqueHub1 = state + "," + city1 + "," + cityHubs.at(city1);
std::string uniqueHub2 = state + "," + city2 + "," + cityHubs.at(city2);
graph.addEdge(uniqueHub1, uniqueHub2, distance);
} else {
if (!cityHubs.count(city1)) std::cerr << "Warning: Hub not defined for city: '" << city1 << "' in line " << lineNumber << " of " << filename << ": " << line << std::endl;
if (!cityHubs.count(city2)) std::cerr << "Warning: Hub not defined for city: '" << city2 << "' in line " << lineNumber << " of " << filename << ": " << line << std::endl;
}
} catch (const std::invalid_argument& ia) {
std::cerr << "Error converting distance to double in line " << lineNumber << " of " << filename << ": " << line << " (" << ia.what() << ")" << std::endl;
} catch (const std::out_of_range& oor) {
std::cerr << "Distance value out of range in line " << lineNumber << " of " << filename << ": " << line << " (" << oor.what() << ")" << std::endl;
}
} else {
std::cerr << "Warning: Skipping malformed line " << lineNumber << " in " << filename << " (expected 4 columns, found " << parts.size() << "): " << line << std::endl;
}
}
file.close();
std::cout << "Successfully processed " << filename << std::endl;
}
// --- Helper Function to load INTER-STATE data ---
void loadInterStateData(Graph& graph, const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error: Could not open file " << filename << std::endl;
return;
}
std::string line;
int lineNumber = 0;
std::unordered_map<std::string, std::string> cityHubs = {
{"Ambala", "Bus Stand (Cantt)"}, {"Karnal", "Bus Stand (ISBT)"}, {"Panchkula", "ISBT Sector 5"},
{"Hisar", "Bus Stand"}, {"Rohtak", "Bus Stand (New)"}, {"Faridabad", "NIT Bus Stand"},
{"Gurugram", "Bus Stand"}, {"Fatehabad", "Bus Stand"}, {"Jind", "Bus Stand"}, {"Sirsa", "Bus Stand"},
{"Panipat", "Bus Stand"}, {"Amritsar", "Bus Stand (ISBT)"}, {"Jalandhar", "Bus Stand (ISBT)"},
{"Ludhiana", "Bus Stand (ISBT)"},{"Pathankot", "Bus Stand"}, {"Gurdaspur", "Bus Stand"},
{"Hoshiarpur", "Bus Stand"},{"Firozpur", "Bus Stand"}, {"Bathinda", "Bus Stand"},
{"Moga", "Bus Stand"}, {"Mansa", "Bus Stand"},{"Patiala", "Bus Stand (New)"},
{"Mohali", "ISBT Mohali (Phase 8)"}, {"Chandigarh", "ISBT Sector 17"},
{"Abohar (Fazilka Dist.)", "Bus Stand"}
};
while (std::getline(file, line)) {
lineNumber++;
if (line.empty() || line.find_first_not_of(" \t\r\n") == std::string::npos || line[0] == '#') {
continue;
}
std::stringstream ss(line);
std::string segment;
std::vector<std::string> parts;
while (std::getline(ss, segment, ',')) {
size_t first = segment.find_first_not_of(" \t\r\n");
if (std::string::npos == first) { parts.push_back(""); continue; }
size_t last = segment.find_last_not_of(" \t\r\n");
parts.push_back(segment.substr(first, (last - first + 1)));
}
if (parts.size() == 5) {
std::string state1 = parts[0];
std::string city1 = parts[1];
std::string state2 = parts[2];
std::string city2 = parts[3];
try {
if (state1.empty() || city1.empty() || state2.empty() || city2.empty() || parts[4].empty()) {
std::cerr << "Error: Empty field(s) in line " << lineNumber << " of " << filename << ": " << line << std::endl;
continue;
}
double distance = std::stod(parts[4]);
if (distance < 0) {
std::cerr << "Error: Negative distance in line " << lineNumber << " of " << filename << ": " << line << std::endl;
continue;
}
if (cityHubs.count(city1) && cityHubs.count(city2)) {
std::string uniqueHub1 = state1 + "," + city1 + "," + cityHubs.at(city1);
std::string uniqueHub2 = state2 + "," + city2 + "," + cityHubs.at(city2);
graph.addEdge(uniqueHub1, uniqueHub2, distance);
} else {
if (!cityHubs.count(city1)) std::cerr << "Warning: Hub not defined for city: '" << city1 << "' in line " << lineNumber << " of " << filename << ": " << line << std::endl;
if (!cityHubs.count(city2)) std::cerr << "Warning: Hub not defined for city: '" << city2 << "' in line " << lineNumber << " of " << filename << ": " << line << std::endl;
}
} catch (const std::invalid_argument& ia) {
std::cerr << "Error converting distance to double in line " << lineNumber << " of " << filename << ": " << line << " (" << ia.what() << ")" << std::endl;
} catch (const std::out_of_range& oor) {
std::cerr << "Distance value out of range in line " << lineNumber << " of " << filename << ": " << line << " (" << oor.what() << ")" << std::endl;
}
} else {
std::cerr << "Warning: Skipping malformed line " << lineNumber << " in " << filename << " (expected 5 columns, found " << parts.size() << "): " << line << std::endl;
}
}
file.close();
std::cout << "Successfully processed " << filename << std::endl;
}
// --- HELPER FUNCTION TO GET USER CHOICE (from a set of strings) ---
std::string getUserChoice(const std::set<std::string>& options, const std::string& prompt) {
if (options.empty()) {
std::cerr << "Error: No options available for prompt: " << prompt << std::endl;
return ""; // Return empty string signifies error
}
std::cout << "\n" << prompt << ":" << std::endl;
// Convert set to vector for indexed access
std::vector<std::string> choices(options.begin(), options.end());
for (size_t i = 0; i < choices.size(); ++i) {
std::cout << " " << (i + 1) << ". " << choices[i] << std::endl;
}
int choiceNum = 0;
while (true) {
std::cout << "Enter choice number (1-" << choices.size() << "): ";
std::string input;
// Use getline to read the whole line, preventing issues with leftover newlines
if (!std::getline(std::cin, input)) {
std::cout << "Input error or end of file detected. Exiting." << std::endl;
exit(1); // Exit if input stream fails
}
try {
// Check if input is empty or just whitespace
if (input.empty() || input.find_first_not_of(" \t") == std::string::npos) {
std::cout << "Invalid input. Please enter a number." << std::endl;
continue; // Ask again
}
choiceNum = std::stoi(input);
// Validate the choice number is within the bounds of the vector indices + 1
if (choiceNum >= 1 && choiceNum <= static_cast<int>(choices.size())) {
return choices[choiceNum - 1]; // Return the chosen string
} else {
std::cout << "Invalid choice number. Please enter a number between 1 and " << choices.size() << "." << std::endl;
}
} catch (const std::invalid_argument& e) {
// Handle cases where stoi fails (e.g., user enters text)
std::cout << "Invalid input. Please enter a number." << std::endl;
} catch (const std::out_of_range& e) {
// Handle cases where the number entered is too large for an int
std::cout << "Input number is out of range. Please try again." << std::endl;
}
// Loop continues if input was invalid
}
}
// --- HELPER FUNCTION TO GET A VALID NUMBER INPUT ---
int getNumericInput(const std::string& prompt, int minVal, int maxVal) {
int count = 0;
while (true) {
std::cout << "\n" << prompt << " (" << minVal << "-" << maxVal << "): ";
std::string input;
if (!std::getline(std::cin, input)) {
std::cout << "Input error or end of file detected. Exiting." << std::endl;
exit(1);
}
try {
if (input.empty() || input.find_first_not_of(" \t") == std::string::npos) {
std::cout << "Invalid input. Please enter a number." << std::endl;
continue;
}
count = std::stoi(input);
if (count >= minVal && count <= maxVal) {
return count; // Valid input received
} else {
std::cout << "Invalid number. Please enter a value between " << minVal << " and " << maxVal << "." << std::endl;
}
} catch (const std::invalid_argument& e) {
std::cout << "Invalid input. Please enter a number." << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "Input number is out of range. Please try again." << std::endl;
}
}
}
// --- HELPER FUNCTION TO GET YES/NO INPUT ---
bool getYesNoInput(const std::string& prompt) {
while (true) {
std::cout << "\n" << prompt << " (y/n): ";
std::string input;
if (!std::getline(std::cin, input)) {
std::cout << "Input error or end of file detected. Exiting." << std::endl;
exit(1);
}
// Convert input to lowercase for case-insensitive comparison
std::transform(input.begin(), input.end(), input.begin(),
[](unsigned char c){ return std::tolower(c); }); // Use lambda for safety
// Remove trailing whitespace which might interfere
size_t last_char = input.find_last_not_of(" \t\n\r\f\v");
if (std::string::npos != last_char) {
input.erase(last_char + 1);
} else {
// Handle case where input is only whitespace
std::cout << "Invalid input. Please enter 'y' or 'n'." << std::endl;
continue;
}
if (input == "y" || input == "yes") {
return true;
} else if (input == "n" || input == "no") {
return false;
} else {
std::cout << "Invalid input. Please enter 'y' or 'n'." << std::endl;
}
}
}
// --- MAIN APPLICATION LOGIC ---
int main() {
// 1. Create Graph and Load Data from Files
Graph mapGraph;
std::cout << "Loading map data..." << std::endl;
loadIntraCityData(mapGraph, "intra_city_distances.txt");
loadInterCityData(mapGraph, "inter_city_distances.txt");
loadInterStateData(mapGraph, "inter_state_distances.txt");
std::cout << "\n--- Map Data Loaded ---" << std::endl;
std::cout << "Total unique locations loaded: " << mapGraph.getNodeCount() << std::endl;
std::cout << "---------------------------------" << std::endl;
// --- 2. Get Ride Details from User ---
// --- START POINT ---
std::cout << "\n=== Select Your Starting Point ===" << std::endl;
std::set<std::string> availableStates = mapGraph.getAllStates();
if (availableStates.empty()) {
std::cerr << "Error: No states available in the map data. Exiting." << std::endl; return 1;
}
std::string startState = getUserChoice(availableStates, "Select Starting State");
std::set<std::string> citiesInStartState = mapGraph.getCitiesInState(startState);
if (citiesInStartState.empty()) {
std::cerr << "Error: No cities found for state '" << startState << "'. Exiting." << std::endl; return 1;
}
std::string startCity = getUserChoice(citiesInStartState, "Select Starting City");
std::set<std::string> locationsInStartCityFull = mapGraph.getLocationsInCity(startState, startCity);
if (locationsInStartCityFull.empty()) {
std::cerr << "Error: No locations found for city '" << startCity << "' in state '" << startState << "'. Exiting." << std::endl; return 1;
}
// Transform full names ("State,City,Location") into just "Location" for display
std::set<std::string> startLocationOptions;
std::transform(locationsInStartCityFull.begin(), locationsInStartCityFull.end(),
std::inserter(startLocationOptions, startLocationOptions.begin()),
// Use lambda with correct Graph object capture
[&mapGraph](const std::string& full) { return mapGraph.formatLocationName(full); });
std::string startLocationName = getUserChoice(startLocationOptions, "Select Starting Location");
// Reconstruct the full node name: State,City,Location
std::string startNode = startState + "," + startCity + "," + startLocationName;
// --- END POINT ---
std::cout << "\n=== Select Your Destination Point ===" << std::endl;
// Reuse availableStates list
std::string endState = getUserChoice(availableStates, "Select Destination State");
std::set<std::string> citiesInEndState = mapGraph.getCitiesInState(endState);
if (citiesInEndState.empty()) {
std::cerr << "Error: No cities found for state '" << endState << "'. Exiting." << std::endl; return 1;
}
std::string endCity = getUserChoice(citiesInEndState, "Select Destination City");
std::set<std::string> locationsInEndCityFull = mapGraph.getLocationsInCity(endState, endCity);
if (locationsInEndCityFull.empty()) {
std::cerr << "Error: No locations found for city '" << endCity << "' in state '" << endState << "'. Exiting." << std::endl; return 1;
}
// Transform full names for display
std::set<std::string> endLocationOptions;
std::transform(locationsInEndCityFull.begin(), locationsInEndCityFull.end(),
std::inserter(endLocationOptions, endLocationOptions.begin()),
[&mapGraph](const std::string& full) { return mapGraph.formatLocationName(full); });
std::string endLocationName = getUserChoice(endLocationOptions, "Select Destination Location");
// Reconstruct the full node name: State,City,Location
std::string endNode = endState + "," + endCity + "," + endLocationName;
// --- GET PRIMARY PASSENGER COUNT ---
int primaryPassengers = getNumericInput("Enter number of passengers travelling from start", 1, 4);
int totalPassengers = primaryPassengers;
// --- RIDE SHARING LOGIC ---
std::vector<std::string> pickupNodes; // Stores the full node names ("State,City,Location") of pickup locations
bool shareRide = getYesNoInput("Do you want to share this ride and pick up others?");
if (shareRide) {
int maxSharers = 4 - primaryPassengers; // Calculate remaining seats
if (maxSharers <= 0) {
std::cout << "Sorry, the cab is already full with your group. Cannot add sharers." << std::endl;
shareRide = false; // Turn off sharing if no space
} else {
// Ask how many *additional* people to pick up
int numSharers = getNumericInput("Enter number of additional passengers to pick up", 1, maxSharers);
// Don't add numSharers to totalPassengers yet, only add successful pickups
std::cout << "\n--- Enter Pickup Locations for Sharers ---" << std::endl;
for (int i = 0; i < numSharers; ++i) {
std::cout << "\n=== Select Pickup Location for Sharer #" << (i + 1) << " ===" << std::endl;
std::string pickupState = getUserChoice(availableStates, "Select Pickup State");
std::set<std::string> citiesInPickupState = mapGraph.getCitiesInState(pickupState);
if (citiesInPickupState.empty()) {
std::cerr << "Error: No cities found for state '" << pickupState << "'. Skipping this sharer." << std::endl; continue;
}
std::string pickupCity = getUserChoice(citiesInPickupState, "Select Pickup City");
std::set<std::string> locationsInPickupCityFull = mapGraph.getLocationsInCity(pickupState, pickupCity);
if (locationsInPickupCityFull.empty()) {
std::cerr << "Error: No locations found for city '" << pickupCity << "'. Skipping this sharer." << std::endl; continue;
}
std::set<std::string> pickupLocationOptions;
std::transform(locationsInPickupCityFull.begin(), locationsInPickupCityFull.end(),
std::inserter(pickupLocationOptions, pickupLocationOptions.begin()),
[&mapGraph](const std::string& full) { return mapGraph.formatLocationName(full); });
std::string pickupLocationName = getUserChoice(pickupLocationOptions, "Select Pickup Location");
// Reconstruct full node name
std::string pickupNode = pickupState + "," + pickupCity + "," + pickupLocationName;
// Basic check: Don't add if it's the same as start or end, or already added
if (pickupNode == startNode || pickupNode == endNode) {
std::cout << "Cannot select the main start or end location as a pickup point. Skipping." << std::endl;
} else if (std::find(pickupNodes.begin(), pickupNodes.end(), pickupNode) != pickupNodes.end()) {
std::cout << "This location has already been added as a pickup point. Skipping." << std::endl;
}
else {
pickupNodes.push_back(pickupNode);
totalPassengers++; // Increment total only if pickup is successfully added
}
}
// If no pickups were successfully added, treat as non-shared
if (pickupNodes.empty()) {
shareRide = false;
std::cout << "No valid pickup locations added. Proceeding as a direct ride." << std::endl;
}
}
}
// --- 3. Find Shortest Path (Direct or Multi-Point) ---
Graph::PathResult result; // Declare result object to store path and distance
if (pickupNodes.empty()) {
// --- Find Direct Path ---
std::cout << "\nCalculating shortest direct path for " << totalPassengers << " passenger(s) from:\n"
<< startNode << "\nTO\n" << endNode << std::endl;
std::cout << "..." << std::endl;
result = mapGraph.findShortestPath(startNode, endNode);
} else {
// --- Find Multi-Point Path ---
std::cout << "\nCalculating optimal multi-point route for " << totalPassengers << " passenger(s)..." << std::endl;
std::cout << " Start: " << startNode << std::endl;
std::cout << " Pickups (" << pickupNodes.size() << "):" << std::endl;
for(size_t i = 0; i < pickupNodes.size(); ++i) {
std::cout << " " << (i+1) << ". " << pickupNodes[i] << std::endl;
}
std::cout << " Destination: " << endNode << std::endl;
std::cout << "..." << std::endl;
// *** Call the multi-point pathfinding function ***
result = mapGraph.findShortestMultiPointPath(startNode, pickupNodes, endNode);
}
// --- 4. Calculate Price & Print Final Result ---
if (result.distance == std::numeric_limits<double>::infinity()) {
std::cout << "\n-----------------------------------------------------" << std::endl;
std::cout << " Sorry, no path could be found between the specified locations." << std::endl;
std::cout << "-----------------------------------------------------" << std::endl;
} else {
// Simple Price Calculation (e.g., Rs. 15 per KM base rate)
const double PRICE_PER_KM = 15.0;
double totalPrice = result.distance * PRICE_PER_KM;
// Optional: Apply a surcharge for the complexity/detour of sharing
double sharingSurcharge = 0.0;
if (!pickupNodes.empty()) {
sharingSurcharge = totalPrice * 0.10; // Example: 10% surcharge
totalPrice += sharingSurcharge;
}
std::cout << "\n--- RIDE CONFIRMED ---" << std::endl;
std::cout << "Total Passengers: " << totalPassengers << std::endl;
std::cout << std::fixed << std::setprecision(1); // Use 1 decimal for distance
std::cout << "Total distance: " << result.distance << " km" << std::endl;
std::cout << std::fixed << std::setprecision(2); // Use 2 decimals for currency
if (sharingSurcharge > 0.0) {
std::cout << "Sharing Surcharge: Rs. " << sharingSurcharge << std::endl;
}
std::cout << "Estimated Total Fare: Rs. " << totalPrice << std::endl;
// Simple price splitting
if (totalPassengers > 0) {
std::cout << "Estimated Fare per Person: Rs. " << (totalPrice / totalPassengers) << std::endl;
}
// --- CORRECTED ROUTE PRINTING ---
std::cout << "\n--- ROUTE ---" << std::endl;
for (size_t i = 0; i < result.path.size(); ++i) {
std::string fullNodeName = result.path[i];
std::string formattedName = mapGraph.formatLocationName(fullNodeName);
// Extract State and City for better context
std::string state, city;
std::stringstream ss(fullNodeName);
std::getline(ss, state, ',');
std::getline(ss, city, ','); // City name is now in 'city'
if (i == 0) {
// START Point - Show full details
std::cout << " Start: " << formattedName << " (" << state << ", " << city << ")" << std::endl;
} else if (i == result.path.size() - 1) {
// END Point - Show full details
std::cout << " End: " << formattedName << " (" << state << ", " << city << ")" << std::endl;
} else {
// Intermediate Points
bool isPickup = false;
// Check if this intermediate node is one of the *requested* pickup points
for(const auto& pickup : pickupNodes) {
if (fullNodeName == pickup) {
isPickup = true;
break;
}
}
if(isPickup) {
// PICKUP Point - Show full details
std::cout << " PICKUP:" << formattedName << " (" << state << ", " << city << ")" << std::endl;
} else {
// VIA Point - Show City and Location Name ONLY for Hubs for brevity
if (formattedName.find("Bus Stand") != std::string::npos ||
formattedName.find("ISBT") != std::string::npos ||
formattedName.find("Railway Station") != std::string::npos)
{
// Avoid printing consecutive identical hub names if they are different nodes
// (e.g., don't print "via: Jind - Bus Stand" right after "via: Rohtak - Bus Stand (New)")
// Check previous step name to avoid redundant "via" lines
if (i > 1) { // Need at least two previous steps to compare
std::string prevFullNodeName = result.path[i-1];
std::string prevFormattedName = mapGraph.formatLocationName(prevFullNodeName);
if (formattedName != prevFormattedName ||
(formattedName.find("Bus Stand") == std::string::npos && formattedName.find("ISBT") == std::string::npos && formattedName.find("Railway Station") == std::string::npos) )
{ // Only print if different from previous or not a hub
std::cout << " via: " << city << " - " << formattedName << std::endl;
}
} else { // Always print the first 'via' hub after start
std::cout << " via: " << city << " - " << formattedName << std::endl;
}
}
// Optional: You could uncomment the line below to see ALL intermediate steps
// std::cout << " -> (" << state << ", " << city << ") " << formattedName << std::endl;
}
}
}
// --- END OF CORRECTED ROUTE PRINTING ---
}
std::cout << "\n--- End of Simulation ---" << std::endl;
return 0;
}