Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | Java program for the above approach ; Function to find probability such that x < y and X belongs to arr1 [ ] and Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Traverse the arr1 [ ] ; Stores the count of elements in arr2 that are greater than arr [ i ] ; Traverse the arr2 [ ] ; If arr2 [ j ] is greater than arr1 [ i ] ; Increment res by y ; Update the value of res ; Return resultant probability ; Driver Code
import java . util . * ; class GFG { static double probability ( int [ ] arr1 , int [ ] arr2 ) { int N = arr1 . length ; int M = arr2 . length ; double res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int y = 0 ; for ( int j = 0 ; j < M ; j ++ ) { if ( arr2 [ j ] > arr1 [ i ] ) y ++ ; } res += y ; } res = ( double ) res / ( double ) ( N * M ) ; return res ; } public static void main ( String [ ] args ) { int [ ] arr1 = { 5 , 2 , 6 , 1 } ; int [ ] arr2 = { 1 , 6 , 10 , 1 } ; System . out . println ( probability ( arr1 , arr2 ) ) ; } }