Find probability of selecting element from kth column after N iterations | Javascript implementation of the above approach ; 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
let n = 4 ; let m = 4 ; function calcProbability ( M , k ) { let dp = new Array ( m ) ; let sum = new Array ( n ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( n ) ; for ( let j = 0 ; j < n ; j ++ ) { dp [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < n ; i ++ ) { sum [ i ] = 0 ; } for ( let j = 0 ; j < n ; j ++ ) { dp [ 0 ] [ j ] = M [ 0 ] [ j ] ; sum [ 0 ] = sum [ 0 ] + dp [ 0 ] [ j ] ; } for ( let i = 1 ; i < m ; i ++ ) { for ( let 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 ] ; } let M = [ [ 1 , 1 , 0 , 3 ] , [ 2 , 3 , 2 , 3 ] , [ 9 , 3 , 0 , 2 ] , [ 2 , 3 , 2 , 2 ] ] ; let k = 3 ; document . write ( calcProbability ( M , k ) ) ;