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 ) ; 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
function findWater ( i , j , X ) { if ( j > i ) { document . write ( " " ) ; } var ll = Math . round ( ( i * ( i + 1 ) ) ) ; glass = Array . from ( { length : ll + 2 } , ( _ , i ) => 0.0 ) ; var 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 ] += X / 2 ; glass [ index + row + 1 ] += X / 2 ; } } return glass [ parseInt ( ( i * ( i - 1 ) / 2 + j - 1 ) ) ] ; } var i = 2 , j = 2 ; var X = 2.0 ; document . write ( " " + " " + findWater ( i , j , X ) ) ;