Displacement from origin after N moves of given distances in specified directions | Java program for the above approach ; Function to find the displacement from the origin and direction after performing the given set of moves ; Stores the distances travelled in the directions North , South , East , and West respectively ; Store the initial position of robot ; Traverse the array B [ ] ; If the current direction is North ; If the current direction is South ; If the current direction is East ; If the current direction is West ; Stores the total vertical displacement ; Stores the total horizontal displacement ; Find the displacement ; Print the displacement and direction after N moves ; Driver Code
class GFG { static void finalPosition ( char [ ] a , int [ ] b , int M ) { int n = 0 , s = 0 , e = 0 , w = 0 ; char p = ' N ' ; for ( int i = 0 ; i < M ; i ++ ) { if ( p == ' N ' ) { if ( a [ i ] == ' U ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' W ' ; w = w + b [ i ] ; } } else if ( p == ' S ' ) { if ( a [ i ] == ' U ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' E ' ; e = e + b [ i ] ; } } else if ( p == ' E ' ) { if ( a [ i ] == ' U ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' S ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' N ' ; n = n + b [ i ] ; } } else if ( p == ' W ' ) { if ( a [ i ] == ' U ' ) { p = ' W ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' D ' ) { p = ' E ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' R ' ) { p = ' N ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' L ' ) { p = ' S ' ; s = s + b [ i ] ; } } } int ver_disp = n - s ; int hor_disp = e - w ; int displacement = ( int ) Math . ceil ( Math . sqrt ( ( ver_disp * ver_disp ) + ( hor_disp * hor_disp ) ) ) ; System . out . print ( displacement + " ▁ " + p ) ; } public static void main ( String args [ ] ) { char [ ] A = { ' U ' , ' R ' , ' R ' , ' R ' , ' R ' } ; int [ ] B = { 1 , 1 , 1 , 1 , 0 } ; int N = 1 ; finalPosition ( A , B , N ) ; } }