In this HackerEarth Final Destination problem solution, Bob and Khatu are stuck in a matrix. The command center sent them a string that decodes to their final destination. Since Bob and Khatu are not good at problem-solving help them to figure out their final destination. They are initially at (0, 0). The string contains L, R, U, D denoting left, right, up, and down. In each command, they will traverse 1 unit distance in the respective direction. For example, if they are at (2, 0) and the command is they will go to (1, 0).
HackerEarth Final Destination problem solution.
#include <bits/stdc++.h>
using namespace std;
int main()
{
string S;
int X=0, Y=0;
cin>>S;
for(int i=0;i<S.size(); i++)
{
if(S[i]=='L')
X--;
else if(S[i]=='R')
X++;
else if(S[i]=='U')
Y++;
else if(S[i]=='D')
Y--;
else
assert(0);
}
cout<<X<<" "<<Y<<endl;
return 0;
}
Second solution
#include<bits/stdc++.h>
using namespace std;
#define vi vector < int >
#define pii pair < int , int >
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define foreach(it,v) for( __typeof((v).begin())it = (v).begin() ; it != (v).end() ; it++ )
#define ll long long
#define llu unsigned long long
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define dbg(x) { cout<< #x << ": " << (x) << endl; }
#define dbg2(x,y) { cout<< #x << ": " << (x) << " , " << #y << ": " << (y) << endl; }
#define all(x) x.begin(),x.end()
#define mset(x,v) memset(x, v, sizeof(x))
#define sz(x) (int)x.size()
int main()
{
string s;
cin >> s;
int x = 0 , y = 0;
int n = sz(s) , i;
assert(1 <= n && n <= 100000);
for(i=0;i<n;i++)
{
if(s[i] == 'L')
{
x--;
}
else if(s[i] == 'R')
{
x++;
}
else if(s[i] == 'U')
{
y++;
}
else if(s[i] == 'D')
{
y--;
}
else
{
assert(0);
}
}
cout << x << " " << y << endl;
return 0;
}
0 Comments