TCS NQT Sober Walk Code Solution

   Sober Walk


Our hoary culture had several great persons since time immemorial and king vikramaditya’s nava ratnas (nine gems) belongs to this ilk.They are named in the following shloka:

Among these, Varahamihira was an astrologer of eminence and his book Brihat Jataak is recokened as the ultimate authority in astrology. He was once talking with Amarasimha,another gem among the nava ratnas and the author of Sanskrit thesaurus, Amarakosha. Amarasimha wanted to know the final position of a person, who starts from the origin 0 0 and travels per following scheme.

  • He first turns and travels 10 units of distance
  • His second turn is upward for 20 units
  • Third turn is to the left for 30 units
  • Fourth turn is the downward for 40 units
  • Fifth turn is to the right(again) for 50 units

… And thus he travels, every time increasing the travel distance by 10 units.

 

Constraints:

2<=n<=1000


Sample Input:

3


Sample Output:

(-20, 20)


Code 

#include <iostream>
using namespace std;

int main()
{
    int n;                                                      //number of turns
    cin >> n;
    
    int flag = 1;                                       //flag to keep track of directions
    int d = 10;                                         //steps increase by 10
    
    int x = 0;                                          //x co-ordinate
    int y = 0;                                         //y co-ordinate
    
    while(n--){                                     //loop till n is not zero
        
        if(flag == 1){                           //flag = 1 RIGHT turn  positive x axis
            flag = 2;                              //next turn will be upward 
            x = x + d;                          //add d to x for positive turn
            d = d + 10;                      //increment d by 10
        }
        else if(flag == 2){                 //flag = 2 UPWARD turn  positive y axis
            flag = 3;                           //next turn will be downward
            y = y + d;                       //add d to y for positive turn
            d = d + 10;                   //increment d by 10
        }
        else if(flag == 3){                //flag = 3 LEFT turn  negative x axis
            flag = 4;                          //next turn will be downward
            x = x - d;                       //substract d from x for negative turn
            d = d + 10;                  //increment d by 10
        }
        else{                               //flag = 4 DOWNWARD turn  negative y axis
            flag = 1;                    //next turn will be Right
            y = y - d;                 //substract d from y for negative turn
            d = d + 10;            //increment d by 10
        }
    }
    cout << "(" << x << "," << y << ")";                //printing output in required format

    return 0;
}


Input

3

Output

(-20,20)

Post a Comment

0 Comments