Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> //cin, cout
- #include <string> //string
- #include <map> //map
- #include <sstream> //istringstream
- #include <cmath> //sqrt
- #include <iomanip> //setprecision
- using namespace std;
- class Solution {
- private:
- string str;
- map<char, int> dir;
- bool tracking = false;
- int j = 0;
- char cdir = '0';
- float dist;
- bool isint(char &c) {
- return c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9';
- }
- void add(int i) {
- string num = str.substr(j, i - 1);
- istringstream iss;
- iss.str(num);
- int inum;
- iss >> inum;
- dir[cdir] += inum;
- //cout << "\tinum=" << inum << "; dir[" << cdir << "]=" << dir[cdir] << endl;
- }
- public:
- Solution(string strin) : str(strin) {
- //parse the string and get the north, south, west, and east distances
- for (unsigned int i = 0; i < str.length(); ++i) {
- char c = str.at(i);
- //cout << "c=" << c << endl;
- if (tracking && i + 1 == str.length()) {
- add(i);
- }
- if (!isint(c)) {
- if (tracking) {
- add(i);
- tracking = false;
- }
- if ((c == 'n' || c == 's' || c == 'w' || c == 'e')) {
- tracking = true;
- j = i + 1;
- cdir = c;
- //cout << "\tnow tracking; j=" << j << endl;
- }
- }
- }
- //cout << "\tc[n]=" << dir['n'] << "; c[s]=" << dir['s'] << "; c[w]=" << dir['w'] << "; c[e]=" << dir['e'] << endl;
- //calculate the distance using pythagorean theorem
- int v = dir['n'] - dir['s'];
- v = v > 0 ? v : -v;
- int h = dir['w'] - dir['e'];
- h = h > 0 ? h : -h;
- dist = sqrt(v*v + h*h);
- }
- float getDistance() {
- return dist;
- }
- };
- int main() {
- string str;
- getline(cin, str);
- Solution solution(str);
- float dist = solution.getDistance();
- cout << std::fixed << std::setprecision(2) << dist << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment