Find probability of selecting element from kth column after N iterations | C ++ 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
#include <bits/stdc++.h> NEW_LINE #define n  4 NEW_LINE #define m  4 NEW_LINE using namespace std ; float calcProbability ( int M [ ] [ m ] , int k ) { float dp [ m ] [ n ] , sum [ n ] ; for ( int j = 0 ; j < n ; j ++ ) { dp [ 0 ] [ j ] = M [ 0 ] [ j ] ; sum [ 0 ] += dp [ 0 ] [ j ] ; } for ( int i = 1 ; i < m ; i ++ ) { for ( int 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 ] ; } int main ( ) { int M [ m ] [ n ] = { { 1 , 1 , 0 , 3 } , { 2 , 3 , 2 , 3 } , { 9 , 3 , 0 , 2 } , { 2 , 3 , 2 , 2 } } ; int k = 3 ; cout << calcProbability ( M , k ) ; return 0 ; }