Program to find amount of water in a given glass | Returns the amount of water in jth glass of ith row ; A row number i has maximum i columns . So input column number must be less than i ; There will be i * ( i + 1 ) / 2 glasses till ith row ( including ith row ) and Initialize all glasses as empty ; Put all water in first glass ; Now let the water flow to the downward glasses till the row number is less than or / equal to i ( given row ) correction : X can be zero for side glasses as they have lower rate to fill ; Fill glasses in a given row . Number of columns in a row is equal to row number ; Get the water from current glass ; Keep the amount less than or equal to capacity in current glass ; Get the remaining amount ; Distribute the remaining amount to the down two glasses ; The index of jth glass in ith row will be i * ( i - 1 ) / 2 + j - 1 ; Driver Code ; Total amount of water
< ? php function findWater ( $ i , $ j , $ X ) { if ( $ j > $ i ) { echo " Incorrect ▁ Input STRNEWLINE " ; return ; } $ glass = array_fill ( 0 , ( int ) ( $ i * ( $ i + 1 ) / 2 ) , 0 ) ; $ index = 0 ; $ glass [ $ index ] = $ X ; for ( $ row = 1 ; $ row < $ i ; ++ $ row ) { for ( $ col = 1 ; $ col <= $ row ; ++ $ col , ++ $ index ) { $ X = $ glass [ $ index ] ; $ glass [ $ index ] = ( $ X >= 1.0 ) ? 1.0 : $ X ; $ X = ( $ X >= 1.0 ) ? ( $ X - 1 ) : 0.0 ; $ glass [ $ index + $ row ] += ( double ) ( $ X / 2 ) ; $ glass [ $ index + $ row + 1 ] += ( double ) ( $ X / 2 ) ; } } return $ glass [ ( int ) ( $ i * ( $ i - 1 ) / 2 + $ j - 1 ) ] ; } $ i = 2 ; $ j = 2 ; $ X = 2.0 ; echo " Amount ▁ of ▁ water ▁ in ▁ jth ▁ " , " glass ▁ of ▁ ith ▁ row ▁ is : ▁ " . str_pad ( findWater ( $ i , $ j , $ X ) , 8 , '0' ) ; ? >