Distance Traveled by Two Trains together in the same Direction | Function to find the distance traveled together ; Stores distance travelled by A ; Stpres distance travelled by B ; Stores the total distance travelled together ; Sum of distance travelled ; Condition for traveling together ; Driver code
function calc_distance ( A , B , n ) { var distance_traveled_A = 0 ; var distance_traveled_B = 0 ; var answer = 0 ; for ( i = 0 ; i < 5 ; i ++ ) { distance_traveled_A += A [ i ] ; distance_traveled_B += B [ i ] ; if ( ( distance_traveled_A == distance_traveled_B ) && ( A [ i ] == B [ i ] ) ) { answer += A [ i ] ; } } return answer ; } var A = [ 1 , 2 , 3 , 2 , 4 ] ; var B = [ 2 , 1 , 3 , 1 , 4 ] ; var N = A . length ; document . write ( calc_distance ( A , B , N ) ) ;