Probability of collision between two trucks | Function to calculate total number of accidents ; String size ; Function to calculate count of all possible collision ; Stores the count of collisions ; Total number of truck in lane b ; Count total number of collisions while traversing the String a ; Function to calculate the probability of collisions ; Evaluate total outcome that is all the possible accident ; Evaluate favourable outcome i . e . , count of collision of trucks ; Print desired probability ; Driver Code ; Function Call
function count_of_accident ( a , b ) { let n = a . length , m = b . length ; if ( n > m ) return ( m * ( m + 1 ) ) / 2 ; else return ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ; } function count_of_collision ( a , b ) { let n = a . length , m = b . length ; let answer = 0 ; let count_of_truck_in_lane_b = 0 ; for ( let i = 0 ; i < m ; i ++ ) if ( b [ i ] == ' ' ) count_of_truck_in_lane_b ++ ; for ( let i = 0 ; i < n && i < m ; i ++ ) { if ( a [ i ] == ' ' ) answer += count_of_truck_in_lane_b ; if ( b [ i ] == ' ' ) count_of_truck_in_lane_b -- ; } return answer ; } function findProbability ( a , b ) { let total_outcome = count_of_accident ( a , b ) ; let favourable_outcome = count_of_collision ( a , b ) ; document . write ( favourable_outcome / total_outcome ) ; } let S = " " , T = " " ; findProbability ( S , T ) ;