C++ and dsa question 1.

Table of contents

No heading

No headings in the article.

Find Displacement : Given a long routes containing N,S,E,W directions, Find the shortest path to reach out the location.

sample input :
SNNNEWE

Sample output :

NNE

solution : -------------

#include<iostream>

using namespace std;

int main () {

char route[1000];
cin.getline(route,1000);

int x = 0;

int y = 0;

for( int i = 0; route[i]!= '\0'; i++) {

switch (route[i]) {
case 'N' : y++;
break ;
case 'S' : y--;
break;
case 'E' : x++;
break;
case 'w' : x--;
break;

}

}

cout << " Final x and y is " << x << y << ".";

if (x>=0 and y>= 0) {

while(y--){
cout<< "N";
}

while(x--){
cout<< "E";

}

while(y--){
cout<< "N";

}

while(y++){
cout<< "S";
}

while(x++){
cout<< "W";

}

}

}