Probability of collision between two trucks | Java 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
import java . util . * ; class GFG { static int count_of_accident ( String a , String b ) { int n = a . length ( ) , m = b . length ( ) ; if ( n > m ) return ( m * ( m + 1 ) ) / 2 ; else return ( n * ( n + 1 ) ) / 2 + ( m - n ) * n ; } static double count_of_collision ( String a , String b ) { int n = a . length ( ) , m = b . length ( ) ; double answer = 0 ; int count_of_truck_in_lane_b = 0 ; for ( int i = 0 ; i < m ; i ++ ) if ( b . charAt ( i ) == ' T ' ) count_of_truck_in_lane_b ++ ; for ( int i = 0 ; i < n && i < m ; i ++ ) { if ( a . charAt ( i ) == ' T ' ) answer += count_of_truck_in_lane_b ; if ( b . charAt ( i ) == ' T ' ) count_of_truck_in_lane_b -- ; } return answer ; } static void findProbability ( String a , String b ) { int total_outcome = count_of_accident ( a , b ) ; double favourable_outcome = count_of_collision ( a , b ) ; System . out . printf ( " % 4f " , favourable_outcome / total_outcome ) ; } public static void main ( String [ ] args ) { String S = " TCCBCTTB " , T = " BTCCBBTT " ; findProbability ( S , T ) ; } }