Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
859 lines (739 loc) · 37.8 KB
/
Copy pathmain.cpp
File metadata and controls
859 lines (739 loc) · 37.8 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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <deque>
const bool primitive_test = false; // Whether or not to run the lazy cout tests
struct edge {
// An edge from A to B may not have the same cost as B to A (not interchangeable)
const std::string start_state = "";
const std::string end_state = "";
const unsigned cost = 0;
};
struct heuristic_data {
const std::string state = "";
const unsigned value = 0;
};
class node {
private:
const std::string state; // State that this node corresponds to
const unsigned heuristic; // Heuristic value of this node
std::vector<edge> edges; // All edges from this node to another, with path cost
std::vector<std::string> path; // List, in order, of states traversed to reach this node
std::vector<unsigned> costs; // List in order of accumulated path costs along path
public:
node(std::string s, unsigned h)
: state(s), heuristic(h) { };
std::string getState() { return state; };
unsigned getHeuristic() { return heuristic; };
unsigned getEvaluationCost() { return costs.at(costs.size() - 1) + heuristic; };
edge getEdge(unsigned i) { return edges.at(i); };
unsigned getEdgeCount() { return edges.size(); };
std::string getPathMember(unsigned i) { return path.at(i); };
unsigned getPathSize() { return path.size(); };
unsigned getCostsMember(unsigned i) { return costs.at(i); };
unsigned getCostsSize() { return costs.size(); };
unsigned getTotalCost() { return costs.at(costs.size() - 1); };
void addEdge(edge e) { edges.push_back(e); };
void addToPath(std::string s) { path.push_back(s); };
void clearPath() { path.clear(); };
void addToCosts(unsigned n) { costs.push_back(n); };
void clearCosts() { costs.clear(); };
};
std::string delTrailingWhitespace(std::string &input) {
return input.substr(0, input.find_last_not_of(" ") + 1);
}
int getHeuristicFromVector(std::string state, std::vector<heuristic_data> data) {
for (unsigned i = 0; i < data.size(); ++i) {
if (data.at(i).state == state) {
return data.at(i).value;
}
}
// Failure
std::cerr << "Failed to find heuristic information for a node of state " << state
<< std::endl;
return -1;
}
int getIndexOfState(std::vector<node> graph, std::string state) {
for (unsigned i = 0; i < graph.size(); ++i) {
if (graph.at(i).getState() == state) {
return i;
}
}
// Failure
std::cerr << "Failed to find a node of state " << state << std::endl;
return -1;
}
node BFS(std::vector<node> graph, unsigned start_index, unsigned goal_index) {
// Frontier and explored contain indices of nodes
std::deque<unsigned> frontier; // Need deque to be able to search the frontier easily
std::vector<unsigned> explored;
frontier.push_front(start_index); // Initial state of frontier is just the start node
// Initialize start state's path and costs vectors
graph.at(start_index).clearPath();
graph.at(start_index).addToPath(graph.at(start_index).getState());
graph.at(start_index).clearCosts();
graph.at(start_index).addToCosts(0);
while (!frontier.empty()) {
unsigned n = frontier.front(); // FIFO
frontier.pop_front();
// Goal test
if (n == goal_index) {
return graph.at(n);
}
explored.push_back(n);
// Tie break: edge that appears earliest in input file (lowest index in node.edges)
// is enqueued first
for (unsigned i = 0; i < graph.at(n).getEdgeCount(); ++i) {
std::string child_state = graph.at(n).getEdge(i).end_state;
unsigned child_state_index = getIndexOfState(graph, child_state);
// Ignore children that are already in explored or frontier
bool already_in_explored = std::find(explored.begin(), explored.end(),
child_state_index) != explored.end();
bool already_in_frontier = std::find(frontier.begin(), frontier.end(),
child_state_index) != frontier.end();
if (!already_in_explored && !already_in_frontier) {
// Set child's path and cost vectors to the parent's
graph.at(child_state_index).clearPath();
for (unsigned j = 0; j < graph.at(n).getPathSize(); ++j) {
graph.at(child_state_index).addToPath(graph.at(n).getPathMember(j));
}
graph.at(child_state_index).clearCosts();
for (unsigned j = 0; j < graph.at(n).getCostsSize(); ++j) {
graph.at(child_state_index).addToCosts(graph.at(n).getCostsMember(j));
}
// Now update path/costs to account for the transition from parent to child
graph.at(child_state_index).addToPath(child_state);
unsigned parentCost =
graph.at(n).getCostsMember(graph.at(n).getCostsSize() - 1);
graph.at(child_state_index).addToCosts(parentCost
+ graph.at(n).getEdge(i).cost);
// Finally add the child to the frontier
frontier.push_back(child_state_index);
}
}
}
// Only reach this line if fail to find a solution in the loop, so return failure
return node("", 0); // Represent failure as a stateless node
}
/* Exact same as BFS except frontier is LIFO */
node DFS(std::vector<node> graph, unsigned start_index, unsigned goal_index) {
// Frontier and explored contain indices of nodes
std::deque<unsigned> frontier; // Need deque to be able to search the frontier easily
std::vector<unsigned> explored;
frontier.push_front(start_index); // Initial state of frontier is just the start node
// Initialize start state's path and costs vectors
graph.at(start_index).clearPath();
graph.at(start_index).addToPath(graph.at(start_index).getState());
graph.at(start_index).clearCosts();
graph.at(start_index).addToCosts(0);
while (!frontier.empty()) {
unsigned n = frontier.back(); // LIFO
frontier.pop_back();
// Goal test
if (n == goal_index) {
return graph.at(n);
}
explored.push_back(n);
// Tie break: edge that appears earliest in input file (lowest index in node.edges)
// is enqueued first
for (unsigned i = 0; i < graph.at(n).getEdgeCount(); ++i) {
std::string child_state = graph.at(n).getEdge(i).end_state;
unsigned child_state_index = getIndexOfState(graph, child_state);
// Ignore children that are already in explored or frontier
bool already_in_explored = std::find(explored.begin(), explored.end(),
child_state_index) != explored.end();
bool already_in_frontier = std::find(frontier.begin(), frontier.end(),
child_state_index) != frontier.end();
if (!already_in_explored && !already_in_frontier) {
// Set child's path and cost vectors to the parent's
graph.at(child_state_index).clearPath();
for (unsigned j = 0; j < graph.at(n).getPathSize(); ++j) {
graph.at(child_state_index).addToPath(graph.at(n).getPathMember(j));
}
graph.at(child_state_index).clearCosts();
for (unsigned j = 0; j < graph.at(n).getCostsSize(); ++j) {
graph.at(child_state_index).addToCosts(graph.at(n).getCostsMember(j));
}
// Now update path/costs to account for the transition from parent to child
graph.at(child_state_index).addToPath(child_state);
unsigned parentCost =
graph.at(n).getCostsMember(graph.at(n).getCostsSize() - 1);
graph.at(child_state_index).addToCosts(parentCost
+ graph.at(n).getEdge(i).cost);
// Finally add the child to the frontier
frontier.push_back(child_state_index);
}
}
}
// Only reach this line if fail to find a solution in the loop, so return failure
return node("", 0); // Represent failure as a stateless node
}
node UCS(std::vector<node> graph, unsigned start_index, unsigned goal_index) {
// Frontier and explored contain indices of nodes
// For convenience, store frontier in descending order of path costs and treat
// the last element as the front of the frontier, so that we can pop that element
// with pop_back
std::vector<unsigned> frontier;
std::vector<unsigned> explored;
frontier.push_back(start_index); // Initial state of frontier is just the start node
// Initialize start state's path and costs vectors
graph.at(start_index).clearPath();
graph.at(start_index).addToPath(graph.at(start_index).getState());
graph.at(start_index).clearCosts();
graph.at(start_index).addToCosts(0);
while (!frontier.empty()) {
unsigned n = frontier.back();
frontier.pop_back();
// Goal test
if (n == goal_index) {
return graph.at(n);
}
explored.push_back(n);
// Create vector of the children indices first
std::vector<unsigned> children;
for (unsigned i = 0; i < graph.at(n).getEdgeCount(); ++i) {
std::string child_state = graph.at(n).getEdge(i).end_state;
unsigned child_state_index = getIndexOfState(graph, child_state);
if (primitive_test) {
std::cout << std::endl << "Checking "
<< graph.at(n).getState() << "'s child "
<< graph.at(child_state_index).getState() << std::endl;
}
// Ignore children that are already in explored
bool already_in_explored = std::find(explored.begin(), explored.end(),
child_state_index) != explored.end();
if (primitive_test) {
std::cout << child_state << " is already in explored?: "
<< already_in_explored << std::endl;
}
if (!already_in_explored) {
auto child_in_frontier = std::find(frontier.begin(), frontier.end(),
child_state_index);
// Node already exists in frontier?
bool already_in_frontier = child_in_frontier != frontier.end();
if (primitive_test) {
std::cout << child_state << " is already in frontier?: "
<< already_in_frontier << std::endl;
}
// Node with lower/equal path cost already exists in frontier?
bool already_in_frontier_better = false;
unsigned parent_cost = graph.at(n).getTotalCost();
unsigned new_cost = parent_cost + graph.at(n).getEdge(i).cost;
if (already_in_frontier) {
unsigned old_cost = graph.at(child_state_index).getTotalCost();
if (old_cost <= new_cost) {
already_in_frontier_better = true;
}
}
if (primitive_test) {
std::cout << child_state
<< " is already in frontier with a better/equal cost?: "
<< already_in_frontier_better << std::endl;
}
// Ignore children that do not improve over what is already in the frontier
if (!already_in_frontier_better) {
if (already_in_frontier) {
if (primitive_test) {
std:: cout << "Deleting inferior path " << child_state
<< " from frontier" << std::endl;
}
// Child is already in frontier but inferior to what we just found,
// so we have to remove it before we add the new child.
frontier.erase(child_in_frontier);
}
// Set child's path and cost vectors to the parent's
graph.at(child_state_index).clearPath();
for (unsigned j = 0; j < graph.at(n).getPathSize(); ++j) {
graph.at(child_state_index).addToPath(graph.at(n).getPathMember(j));
}
graph.at(child_state_index).clearCosts();
for (unsigned j = 0; j < graph.at(n).getCostsSize(); ++j) {
unsigned cost = graph.at(n).getCostsMember(j);
graph.at(child_state_index).addToCosts(cost);
}
// Now update path/costs to account for the transition from
// parent to child
graph.at(child_state_index).addToPath(child_state);
graph.at(child_state_index).addToCosts(parent_cost +
graph.at(n).getEdge(i).cost);
if (primitive_test) {
std::cout << "Path of " << child_state << " is ";
unsigned pathSize = graph.at(child_state_index).getPathSize();
for (unsigned j = 0; j < pathSize; ++j) {
std::cout << graph.at(child_state_index).getPathMember(j) << " ";
}
std::cout << std::endl;
std::cout << "Costs of " << child_state << " are ";
unsigned costs_size = graph.at(child_state_index).getCostsSize();
for (unsigned j = 0; j < costs_size; ++j) {
std::cout << graph.at(child_state_index).getCostsMember(j)
<< " ";
}
std::cout << std::endl;
}
// Finally, we can add the child to the children vector for handling
children.push_back(child_state_index);
}
}
}
if (primitive_test) {
if (children.size() > 0) {
std::cout << std::endl << "Children vector is ";
for (unsigned i = 0; i < children.size(); ++i) {
std::cout << graph.at(children.at(i)).getState() << " ";
}
std::cout << std::endl;
} else {
std::cout << std::endl << "Children vector is empty"
<< " (none of this node's children need to be added to frontier)"
<< std::endl;
}
}
// Still have to handle tie breaks: if multiple children have the same cost, insert
// them in the order they appear in the input file, and if inserting a child with
// equal path cost to a node that already exists in the frontier,
// enqueue the child right after that node.
for (unsigned i = 0; i < children.size(); ++i) {
unsigned child_cost = graph.at(children.at(i)).getTotalCost();
// Vector of indices in the children vector that this child ties with
std::vector<unsigned> children_vector_tie_indices;
for (unsigned j = 0; j < children.size(); ++j) {
if (j != i && child_cost == graph.at(children.at(j)).getTotalCost()) {
children_vector_tie_indices.push_back(j);
}
}
if (primitive_test) {
if (children_vector_tie_indices.size() > 0) {
std::cout << std::endl << "Found ties: ";
for (unsigned j = 0; j < children_vector_tie_indices.size(); ++j) {
unsigned tie_children_index = children_vector_tie_indices.at(j);
unsigned tie_graph_index = children.at(tie_children_index);
std::cout << graph.at(tie_graph_index).getState() << " ";
}
}
std::cout << std::endl;
}
// Find where the child and the children it ties with, if any, should be
// inserted. Insert at end of vector (front of frontier) if fail to find
// any nodes in frontier with cost less than or equal to the child's cost
unsigned child_insert_position = frontier.size();
bool found_insert_position = false;
for (unsigned j = 0; j < frontier.size() && !found_insert_position; ++j) {
if (graph.at(frontier.at(j)).getTotalCost() <= child_cost) {
child_insert_position = j;
found_insert_position = true;
}
}
if (primitive_test) {
std::cout << "Frontier before adding child "
<< graph.at(children.at(i)).getState() << " and ties: ";
for (unsigned j = 0; j < frontier.size(); ++j) {
std::cout << graph.at(frontier.at(j)).getState() << " ";
}
std::cout << std::endl;
}
// Add the children to the frontier. For ties, the node earliest in the
// input file (= lowest index in children vector) goes closest to the front
// of the frontier (front of frontier = last element, which has lowest cost)
frontier.insert(frontier.begin()+child_insert_position, children.at(i));
for (unsigned j = 0; j < children_vector_tie_indices.size(); ++j) {
unsigned tie_children_index = children_vector_tie_indices.at(j);
unsigned tie_graph_index = children.at(tie_children_index);
frontier.insert(frontier.begin()+child_insert_position, tie_graph_index);
}
if (primitive_test) {
std::cout << "Frontier after adding child "
<< graph.at(children.at(i)).getState() << " and ties: ";
for (unsigned j = 0; j < frontier.size(); ++j) {
std::cout << graph.at(frontier.at(j)).getState() << " ";
}
std::cout << std::endl;
}
// Delete the children that tied from the children vector, so they aren't
// added a second time
for (unsigned j = 0; j < children_vector_tie_indices.size(); ++j) {
children.erase(children.begin()+children_vector_tie_indices.at(j));
}
}
}
// Only reach this line if fail to find a solution in the loop, so return failure
return node("", 0); // Represent failure as a stateless node
}
/* Exact same as UCS except path cost -> path cost + heuristic */
node A_STAR(std::vector<node> graph, unsigned start_index, unsigned goal_index) {
// Frontier and explored contain indices of nodes
// For convenience, store frontier in descending order of evaluation costs and treat
// the last element as the front of the frontier, so that we can pop that element
// with pop_back
std::vector<unsigned> frontier;
std::vector<unsigned> explored;
frontier.push_back(start_index); // Initial state of frontier is just the start node
// Initialize start state's path and costs vectors
// Note that the costs vector is still only path costs, just like in UCS
graph.at(start_index).clearPath();
graph.at(start_index).addToPath(graph.at(start_index).getState());
graph.at(start_index).clearCosts();
graph.at(start_index).addToCosts(0);
while (!frontier.empty()) {
unsigned n = frontier.back();
frontier.pop_back();
// Goal test
if (n == goal_index) {
return graph.at(n);
}
explored.push_back(n);
// Create vector of the children indices first
std::vector<unsigned> children;
for (unsigned i = 0; i < graph.at(n).getEdgeCount(); ++i) {
std::string child_state = graph.at(n).getEdge(i).end_state;
unsigned child_state_index = getIndexOfState(graph, child_state);
if (primitive_test) {
std::cout << std::endl << "Checking "
<< graph.at(n).getState() << "'s child "
<< graph.at(child_state_index).getState() << std::endl;
}
// Ignore children that are already in explored
bool already_in_explored = std::find(explored.begin(), explored.end(),
child_state_index) != explored.end();
if (primitive_test) {
std::cout << child_state << " is already in explored?: "
<< already_in_explored << std::endl;
}
if (!already_in_explored) {
auto child_in_frontier = std::find(frontier.begin(), frontier.end(),
child_state_index);
// Node already exists in frontier?
bool already_in_frontier = child_in_frontier != frontier.end();
if (primitive_test) {
std::cout << child_state << " is already in frontier?: "
<< already_in_frontier << std::endl;
}
// Node with lower/equal evaluation cost already exists in frontier?
bool already_in_frontier_better = false;
unsigned parent_path_cost = graph.at(n).getTotalCost();
unsigned child_path_cost = parent_path_cost + graph.at(n).getEdge(i).cost;
unsigned child_heuristic = graph.at(child_state_index).getHeuristic();
// Cannot use getEvaluationCost since child node hasn't had its costs vector
// updated yet, so have to calculate it like this
unsigned new_cost = child_path_cost + child_heuristic;
if (already_in_frontier) {
unsigned old_cost = graph.at(child_state_index).getEvaluationCost();
if (old_cost <= new_cost) {
already_in_frontier_better = true;
}
}
if (primitive_test) {
std::cout << child_state
<< " is already in frontier with a better/equal cost?: "
<< already_in_frontier_better << std::endl;
}
// Ignore children that do not improve over what is already in the frontier
if (!already_in_frontier_better) {
if (already_in_frontier) {
if (primitive_test) {
std:: cout << "Deleting inferior path " << child_state
<< " from frontier" << std::endl;
}
// Child is already in frontier but inferior to what we just found,
// so we have to remove it before we add the new child.
frontier.erase(child_in_frontier);
}
// Set child's path and cost vectors to the parent's
graph.at(child_state_index).clearPath();
for (unsigned j = 0; j < graph.at(n).getPathSize(); ++j) {
graph.at(child_state_index).addToPath(graph.at(n).getPathMember(j));
}
graph.at(child_state_index).clearCosts();
for (unsigned j = 0; j < graph.at(n).getCostsSize(); ++j) {
unsigned cost = graph.at(n).getCostsMember(j);
graph.at(child_state_index).addToCosts(cost);
}
// Now update path/costs to account for the transition from
// parent to child
graph.at(child_state_index).addToPath(child_state);
graph.at(child_state_index).addToCosts(parent_path_cost +
graph.at(n).getEdge(i).cost);
if (primitive_test) {
std::cout << "Path of " << child_state << " is ";
unsigned pathSize = graph.at(child_state_index).getPathSize();
for (unsigned j = 0; j < pathSize; ++j) {
std::cout << graph.at(child_state_index).getPathMember(j) << " ";
}
std::cout << std::endl;
std::cout << "Costs of " << child_state << " are ";
unsigned costs_size = graph.at(child_state_index).getCostsSize();
for (unsigned j = 0; j < costs_size; ++j) {
std::cout << graph.at(child_state_index).getCostsMember(j)
<< " ";
}
std::cout << std::endl;
}
// Finally, we can add the child to the children vector for handling
children.push_back(child_state_index);
}
}
}
if (primitive_test) {
if (children.size() > 0) {
std::cout << std::endl << "Children vector is ";
for (unsigned i = 0; i < children.size(); ++i) {
std::cout << graph.at(children.at(i)).getState() << " ";
}
std::cout << std::endl;
} else {
std::cout << std::endl << "Children vector is empty"
<< " (none of this node's children need to be added to frontier)"
<< std::endl;
}
}
// Still have to handle tie breaks: if multiple children have the same cost, insert
// them in the order they appear in the input file, and if inserting a child with
// equal evaluation cost to a node that already exists in the frontier,
// enqueue the child right after that node.
for (unsigned i = 0; i < children.size(); ++i) {
unsigned child_evaluation_cost = graph.at(children.at(i)).getEvaluationCost();
// Vector of indices in the children vector that this child ties with
std::vector<unsigned> children_vector_tie_indices;
for (unsigned j = 0; j < children.size(); ++j) {
unsigned evaluation_cost = graph.at(children.at(j)).getEvaluationCost();
bool tie = (child_evaluation_cost == evaluation_cost);
if (j != i && tie) {
children_vector_tie_indices.push_back(j);
}
}
if (primitive_test) {
if (children_vector_tie_indices.size() > 0) {
std::cout << std::endl << "Found ties: ";
for (unsigned j = 0; j < children_vector_tie_indices.size(); ++j) {
unsigned tie_children_index = children_vector_tie_indices.at(j);
unsigned tie_graph_index = children.at(tie_children_index);
std::cout << graph.at(tie_graph_index).getState() << " ";
}
}
std::cout << std::endl;
}
// Find where the child and the children it ties with, if any, should be
// inserted. Insert at end of vector (front of frontier) if fail to find
// any nodes in frontier with cost less than or equal to the child's cost
unsigned child_insert_position = frontier.size();
bool found_insert_position = false;
for (unsigned j = 0; j < frontier.size() && !found_insert_position; ++j) {
if (graph.at(frontier.at(j)).getEvaluationCost() <= child_evaluation_cost) {
child_insert_position = j;
found_insert_position = true;
}
}
if (primitive_test) {
std::cout << "Frontier before adding child "
<< graph.at(children.at(i)).getState() << " and ties: ";
for (unsigned j = 0; j < frontier.size(); ++j) {
std::cout << graph.at(frontier.at(j)).getState() << " ";
}
std::cout << std::endl;
}
// Add the children to the frontier. For ties, the node earliest in the
// input file (= lowest index in children vector) goes closest to the front
// of the frontier (front of frontier = last element, which has lowest cost)
frontier.insert(frontier.begin()+child_insert_position, children.at(i));
for (unsigned j = 0; j < children_vector_tie_indices.size(); ++j) {
unsigned tie_children_index = children_vector_tie_indices.at(j);
unsigned tie_graph_index = children.at(tie_children_index);
frontier.insert(frontier.begin()+child_insert_position, tie_graph_index);
}
if (primitive_test) {
std::cout << "Frontier after adding child "
<< graph.at(children.at(i)).getState() << " and ties: ";
for (unsigned j = 0; j < frontier.size(); ++j) {
std::cout << graph.at(frontier.at(j)).getState() << " ";
}
std::cout << std::endl;
}
// Delete the children that tied from the children vector, so they aren't
// added a second time
for (unsigned j = 0; j < children_vector_tie_indices.size(); ++j) {
children.erase(children.begin()+children_vector_tie_indices.at(j));
}
}
}
// Only reach this line if fail to find a solution in the loop, so return failure
return node("", 0); // Represent failure as a stateless node
}
node getSolution(std::vector<node> graph,
unsigned start_index, unsigned goal_index, std::string alg) {
if (alg == "BFS") {
return BFS(graph, start_index, goal_index);
} else if (alg == "DFS") {
return DFS(graph, start_index, goal_index);
} else if (alg == "UCS") {
return UCS(graph, start_index, goal_index);
} else if (alg == "A*") {
return A_STAR(graph, start_index, goal_index);
} else {
std::cerr << "Invalid algorithm name \"" << alg << "\". Defaulting to UCS." << std::endl;
return UCS(graph, start_index, goal_index);
}
}
int main() {
/* First collect all data from input.txt */
const std::string input_filename = "input.txt";
std::ifstream ifs(input_filename, std::ios::in);
if (ifs.fail()) {
std::cerr << "Failed to open " << input_filename << std::endl;
return -1;
}
// First three lines are always the algorithm followed by start and goal state
std::string algo, start_state, goal_state;
std::getline(ifs, algo);
algo = delTrailingWhitespace(algo);
std::getline(ifs, start_state);
start_state = delTrailingWhitespace(start_state);
std::getline(ifs, goal_state);
goal_state = delTrailingWhitespace(goal_state);
// Grab the number of live traffic lines as an (unsigned) integer
std::string live_line_count_string;
std::getline(ifs, live_line_count_string);
const unsigned live_lines = static_cast<unsigned>(stoi(live_line_count_string));
// Create vector containing all the live traffic data (graph edges)
std::vector<edge> live_traffic_data;
for (unsigned i = 0; i < live_lines; ++i) {
std::string line;
std::getline(ifs, line);
line = delTrailingWhitespace(line);
// Assuming data is separated by single spaces
unsigned first_space_pos = line.find_first_of(" ");
unsigned last_space_pos = line.find_last_of(" ");
edge e = {
line.substr(0, first_space_pos),
line.substr(first_space_pos + 1, last_space_pos - first_space_pos - 1),
static_cast<unsigned>(stoi(line.substr(last_space_pos + 1, line.size() - 1)))
};
live_traffic_data.push_back(e);
}
// Grab the number of sunday traffic lines as an (unsigned) integer
std::string sunday_line_count_string;
std::getline(ifs, sunday_line_count_string);
const unsigned sunday_lines = static_cast<unsigned>(stoi(sunday_line_count_string));
// Create vector containing all the sunday traffic data
std::vector<heuristic_data> sunday_traffic_data;
for (unsigned i = 0; i < sunday_lines; ++i) {
std::string line;
std::getline(ifs, line);
line = delTrailingWhitespace(line);
// Assuming data is separated by a single space
unsigned space_pos = line.find_first_of(" ");
heuristic_data d = {
line.substr(0, space_pos),
static_cast<unsigned>(stoi(line.substr(space_pos + 1, line.size() - 1)))
};
sunday_traffic_data.push_back(d);
}
// Test that the data was read correctly
if (primitive_test) {
std::cout << "Edges: " << std::endl;
for (unsigned i = 0; i < live_traffic_data.size(); ++i) {
std::cout << "From " << live_traffic_data.at(i).start_state
<< " to " << live_traffic_data.at(i).end_state
<< " with cost " << live_traffic_data.at(i).cost
<< std::endl;
}
std::cout << "Heuristics: " << std::endl;
for (unsigned i = 0; i < sunday_traffic_data.size(); ++i) {
std::cout << "Heuristic of state " << sunday_traffic_data.at(i).state
<< " is " << sunday_traffic_data.at(i).value << std::endl;
}
std::cout << std::endl;
}
// All data has been read, won't need input file again
ifs.close();
/* Generate the graph using all the provided data */
// First all nodes that have edges leading away from them
std::vector<node> graph;
for (unsigned i = 0; i < live_traffic_data.size(); ++i) {
const std::string node_state = live_traffic_data.at(i).start_state;
// Does a node at the start of this edge already exist?
bool node_already_exists = false;
int existing_node_index = -1;
for (unsigned j = 0; j < graph.size(); ++j) {
if (graph.at(j).getState() == node_state) {
node_already_exists = true;
existing_node_index = j;
}
}
if (node_already_exists) { // If so, just add this edge to the existing node
graph.at(existing_node_index).addEdge(live_traffic_data.at(i));
} else { // Otherwise, create new node with this edge
// Have to set the heuristic value while creating a new node
const int h = getHeuristicFromVector(node_state, sunday_traffic_data);
node n(node_state, h);
n.addEdge(live_traffic_data.at(i));
graph.push_back(n);
}
}
// Now go through and add the node(s) that only exist at the ends of edges, if any
for (unsigned i = 0; i < live_traffic_data.size(); ++i) {
const std::string node_state = live_traffic_data.at(i).end_state;
// Does the node at the end of this edge already exist?
bool node_already_exists = false;
for (unsigned j = 0; j < graph.size(); ++j) {
if (graph.at(j).getState() == node_state) {
node_already_exists = true;
}
}
// If not, it must be a node with no edges leaving it, since already added the rest
if (!node_already_exists) {
const int h = getHeuristicFromVector(node_state, sunday_traffic_data);
node n(node_state, h);
graph.push_back(n);
}
}
// Test that the graph is constructed correctly
if (primitive_test) {
std::cout << "Graph vector: " << std::endl;
for (unsigned i = 0; i < graph.size(); ++i) {
std::cout << "Node: " << graph.at(i).getState()
<< ", Heuristic: " << graph.at(i).getHeuristic() << std::endl;
std::cout << "Edges: " << std::endl;
unsigned edgeCount = graph.at(i).getEdgeCount();
if (edgeCount > 0) {
for (unsigned j = 0; j < graph.at(i).getEdgeCount(); ++j) {
std::cout << "From " << graph.at(i).getEdge(j).start_state
<< " to " << graph.at(i).getEdge(j).end_state
<< " with cost " << graph.at(i).getEdge(j).cost
<< std::endl;
}
} else {
std::cout << "None." << std::endl;
}
}
}
/* Apply the specified algorithm and find out the solution */
// Start state is not necessarily the first node in the graph vector
unsigned start_index = getIndexOfState(graph, start_state);
unsigned goal_index = getIndexOfState(graph, goal_state);
node solution = getSolution(graph, start_index, goal_index, algo);
if (solution.getState() == "") { // Empty state represents failure
std::cout << "Failed to find a solution.";
return -1;
}
if (primitive_test) {
std::cout << "Found solution node of state " << solution.getState()
<< " using " << algo << std::endl;
std::cout << "Solution path is: " << std::endl;
for (unsigned i = 0; i < solution.getPathSize(); ++i) {
std::cout << solution.getPathMember(i)
<< " reached with total cost "
<< solution.getCostsMember(i) << std::endl;
}
}
/* Output the solution to output.txt */
const std::string output_filename = "output.txt";
std::ofstream ofs(output_filename, std::ios::out);
for (unsigned i = 0; i < solution.getPathSize(); ++i) {
ofs << solution.getPathMember(i) << " "
<< solution.getCostsMember(i) << " " << std::endl;
}
ofs.close();
return 0;
}