-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem59.cpp
More file actions
85 lines (71 loc) · 1.71 KB
/
problem59.cpp
File metadata and controls
85 lines (71 loc) · 1.71 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
#include <iostream>
#include <set>
#include <string>
using namespace std;
class InputReader {
public:
string steps;
void readInput() {
cout << "Enter Benny's movement path: ";
getline(cin, steps);
}
bool isValidPath() {
for (char c : steps) {
if (c != 'L' && c != 'R' && c != 'U' && c != 'D')
return false;
}
return true;
}
bool isWithinConstraints() {
int len = steps.length();
return (len >= 1 && len <= 100000);
}
};
class PathTracker {
private:
set<pair<int, int>> visited;
int x, y;
public:
PathTracker() : x(0), y(0) {
visited.insert({0, 0});
}
int countSlips(const string& moves) {
int slips = 0;
for (char move : moves) {
switch (move) {
case 'L': x--; break;
case 'R': x++; break;
case 'U': y++; break;
case 'D': y--; break;
}
pair<int, int> pos = {x, y};
if (visited.count(pos))
slips++;
else
visited.insert(pos);
}
return slips;
}
};
class ResultPrinter {
public:
static void display(int slips) {
cout << "Total slips: " << slips << endl;
}
};
int main() {
InputReader input;
input.readInput();
if (!input.isWithinConstraints()) {
cout << "String length must be between 1 and 10^5." << endl;
return 1;
}
if (!input.isValidPath()) {
cout << "Enter only L, R, U, D characters." << endl;
return 1;
}
PathTracker tracker;
int slips = tracker.countSlips(input.steps);
ResultPrinter::display(slips);
return 0;
}