Displacement from origin after N moves of given distances in specified directions | 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
function finalPosition ( a , b , M ) { let n = 0 , s = 0 , e = 0 , w = 0 ; let p = ' ' ; for ( let i = 0 ; i < M ; i ++ ) { if ( p == ' ' ) { if ( a [ i ] == ' ' ) { p = ' ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; w = w + b [ i ] ; } } else if ( p == ' ' ) { if ( a [ i ] == ' ' ) { p = ' ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; e = e + b [ i ] ; } } else if ( p == ' ' ) { if ( a [ i ] == ' ' ) { p = ' ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; s = s + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; n = n + b [ i ] ; } } else if ( p == ' ' ) { if ( a [ i ] == ' ' ) { p = ' ' ; w = w + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; e = e + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; n = n + b [ i ] ; } else if ( a [ i ] == ' ' ) { p = ' ' ; s = s + b [ i ] ; } } } let ver_disp = n - s ; let hor_disp = e - w ; let displacement = Math . ceil ( Math . sqrt ( ( ver_disp * ver_disp ) + ( hor_disp * hor_disp ) ) ) ; document . write ( displacement + " " + p ) ; } let A = [ ' ' , ' ' , ' ' , ' ' , ' ' ] ; let B = [ 1 , 1 , 1 , 1 , 0 ] ; let N = 1 ; finalPosition ( A , B , N ) ;