Shortest direction

PROBLEM :

A person wants to go from origin to a particular location, he can move in only 4 directions(i.e East, West, North, South) but his friend gave him a long route, help a person to find minimum Moves so that he can reach to the destination.

Note: You need to print the lexicographically sorted string. Assume the string will have only ‘E’ ‘N’ ‘S’ ‘W’ characters.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is S, S is the long route (string).

Output:

Print minimum Moves so that he can reach to the destination.

Constraints:

1 = T = 100
1 = S length = 1000

Example:

Input
2
SSSNEEEW
NESNWES

Output
EESS
E

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
void Shortest_direction(string ) ;
int main()
 {
int t ;
string str ;
cin>>t ;
while(t--)
{
   cin>>str ;
   Shortest_direction(str) ;
   cout<<endl ;
}
return 0;
}

void Shortest_direction(string str)
{
    int e,w,n,s,l,i ;
    e=0 ;
    w=0 ;
    n=0 ;
    s=0 ;
   
    l=str.length() ;
    for(i=0;i<l;i++)
    {
        if(str[i]=='E')
            e++ ;
        else if(str[i]=='W')
            w++ ;
        else if(str[i]=='N')
            n++ ;
        else if(str[i]=='S')
            s++ ;
    }
   
    if(e>w)
    {
        e=e-w ;
        w=0 ;
    }
    else
    {
        w=w-e ;
        e=0 ;
    }
   
    if(n>s)
    {
        n=n-s ;
        s=0 ;
    }
    else
    {
        s=s-n ;
        n=0 ;
    }
   
    int k=0 ;
    while(e--)
        cout<<"E" ;
    while(n--)
        cout<<"N" ;
    while(s--)
        cout<<"S" ;
    while(w--)
        cout<<"W" ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )