Probability of collision between two trucks | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; double count_of_accident ( string a , string b ) { int n = a . size ( ) , m = b . size ( ) ; if ( n > m ) return ( m * ( m + 1 ) ) / 2 ; else return ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ; } double count_of_collision ( string a , string b ) { int n = a . size ( ) , m = b . size ( ) ; int answer = 0 ; int count_of_truck_in_lane_b = 0 ; for ( int i = 0 ; i < m ; i ++ ) if ( b [ i ] == ' T ' ) count_of_truck_in_lane_b ++ ; for ( int i = 0 ; i < n && i < m ; i ++ ) { if ( a [ i ] == ' T ' ) answer += count_of_truck_in_lane_b ; if ( b [ i ] == ' T ' ) count_of_truck_in_lane_b -- ; } return answer ; } double findProbability ( string a , string b ) { double total_outcome = count_of_accident ( a , b ) ; double favourable_outcome = count_of_collision ( a , b ) ; cout << favourable_outcome / total_outcome ; } int main ( ) { string S = " TCCBCTTB " , T = " BTCCBBTT " ; findProbability ( S , T ) ; return 0 ; }