Find probability of selecting element from kth column after N iterations | Function to calculate probability ; declare dp [ ] [ ] and sum [ ] ; precalculate the first row ; calculate the probability for each element and update dp table ; return result ; Driver code
< ? php function calcProbability ( $ M , $ k ) { $ m = 4 ; $ n = 4 ; $ dp = array ( ) ; $ sum = array ( ) ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { $ dp [ 0 ] [ $ j ] = $ M [ 0 ] [ $ j ] ; $ sum [ 0 ] += $ dp [ 0 ] [ $ j ] ; } for ( $ i = 1 ; $ i < $ m ; $ i ++ ) { for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { $ dp [ $ i ] [ $ j ] += $ dp [ $ i - 1 ] [ $ j ] / $ sum [ $ i - 1 ] + $ M [ $ i ] [ $ j ] ; $ sum [ $ i ] += $ dp [ $ i ] [ $ j ] ; } } return $ dp [ $ n - 1 ] [ $ k - 1 ] / $ sum [ $ n - 1 ] ; } $ M = array ( array ( 1 , 1 , 0 , 3 ) , array ( 2 , 3 , 2 , 3 ) , array ( 9 , 3 , 0 , 2 ) , array ( 2 , 3 , 2 , 2 ) ) ; $ k = 3 ; echo calcProbability ( $ M , $ k ) ; ? >