The Wayback Machine - https://web.archive.org/web/20240705213506/https://www.geeksforgeeks.org/find-water-in-a-glass/
Open In App

Program to find amount of water in a given glass

Last Updated : 27 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There are some glasses with equal capacity as 1 litre. The glasses are kept as follows: 

                   1
                 2   3
              4    5    6
            7    8    9   10

You can put water to the only top glass. If you put more than 1-litre water to 1st glass, water overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on. 

If you have X litre of water and you put that water in a top glass, how much water will be contained by the jth glass in an ith row?

Example. If you will put 2 litres on top. 
1st – 1 litre 
2nd – 1/2 litre 
3rd – 1/2 litre

 For 2 Liters Water

The approach is similar to Method 2 of the Pascal’s Triangle. If we take a closer look at the problem, the problem boils down to Pascal’s Triangle.  

                           1   ---------------- 1
                 2   3 ---------------- 2
                      4    5    6  ------------ 3
            7    8    9   10  --------- 4

Each glass contributes to the two glasses down the glass. Initially, we put all water in the first glass. Then we keep 1 litre (or less than 1 litre) in it and move rest of the water to two glasses down to it. We follow the same process for the two glasses and all other glasses till the ith row. There will be i*(i+1)/2 glasses till ith row. 

Recommended Practice

C++




// Program to find the amount of water in j-th glass
// of i-th row
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Returns the amount of water in jth glass of ith row
float findWater(int i, int j, float X)
{
    // A row number i has maximum i columns. So input
    // column number must be less than i
    if (j > i)
    {
        printf("Incorrect Inputn");
        exit(0);
    }
 
    // There will be i*(i+1)/2 glasses till ith row
    // (including ith row)
    float glass[i * (i + 1) / 2];
 
    // Initialize all glasses as empty
    memset(glass, 0, sizeof(glass));
 
    // Put all water in first glass
    int index = 0;
    glass[index] = X;
 
    // 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
    for (int row = 1; row <= i ; ++row)
    {
        // Fill glasses in a given row. Number of
        // columns in a row is equal to row number
        for (int col = 1; col <= row; ++col, ++index)
        {
            // Get the water from current glass
            X = glass[index];
 
            // Keep the amount less than or equal to
            // capacity in current glass
            glass[index] = (X >= 1.0f) ? 1.0f : X;
 
            // Get the remaining amount
            X = (X >= 1.0f) ? (X - 1) : 0.0f;
 
            // Distribute the remaining amount to
            // the down two glasses
            glass[index + row] += X / 2;
            glass[index + row + 1] += X / 2;
        }
    }
 
    // The index of jth glass in ith row will
    // be i*(i-1)/2 + j - 1
    return glass[i*(i-1)/2 + j - 1];
}
 
// Driver program to test above function
int main()
{
    int i = 2, j = 2;
    float X = 2.0; // Total amount of water
 
    printf("Amount of water in jth glass of ith row is: %f",
            findWater(i, j, X));
 
    return 0;
}


Java




// Program to find the amount
/// of water in j-th glass
// of i-th row
import java.lang.*;
 
class GFG
{
// Returns the amount of water
// in jth glass of ith row
static float findWater(int i, int j,
                       float X)
{
// A row number i has maximum i
// columns. So input column
// number must be less than i
if (j > i)
{
    System.out.println("Incorrect Input");
    System.exit(0);
}
 
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
int ll = Math.round((i * (i + 1) ));
float[] glass = new float[ll + 2];
 
// Put all water in first glass
int index = 0;
glass[index] = X;
 
// 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
for (int row = 1; row <= i ; ++row)
{
    // Fill glasses in a given row. Number of
    // columns in a row is equal to row number
    for (int col = 1;
             col <= row; ++col, ++index)
    {
        // Get the water from current glass
        X = glass[index];
 
        // Keep the amount less than or
        // equal to capacity in current glass
        glass[index] = (X >= 1.0f) ? 1.0f : X;
 
        // Get the remaining amount
        X = (X >= 1.0f) ? (X - 1) : 0.0f;
 
        // Distribute the remaining amount 
        // to the down two glasses
        glass[index + row] += X / 2;
        glass[index + row + 1] += X / 2;
    }
}
 
// The index of jth glass in ith
// row will be i*(i-1)/2 + j - 1
return glass[(int)(i * (i - 1) /
                   2 + j - 1)];
}
 
// Driver Code
public static void main(String[] args)
{
    int i = 2, j = 2;
    float X = 2.0f; // Total amount of water
    System.out.println("Amount of water in jth " +
                         "glass of ith row is: " +
                              findWater(i, j, X));
}
}
 
// This code is contributed by mits


Python3




# Program to find the amount
# of water in j-th glass of
# i-th row
 
# Returns the amount of water
# in jth glass of ith row
def findWater(i, j, X):
    # A row number i has maximum
    # i columns. So input column
    # number must be less than i
    if (j > i):
        print("Incorrect Input");
        return;
 
    # There will be i*(i+1)/2
    # glasses till ith row
    # (including ith row)
    # and Initialize all glasses
    # as empty
    glass = [0]*int(i *(i + 1) / 2);
 
    # Put all water
    # in first glass
    index = 0;
    glass[index] = X;
 
    # 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
    for row in range(1,i):
        # Fill glasses in a given
        # row. Number of columns
        # in a row is equal to row number
        for col in range(1,row+1):
            # Get the water
            # from current glass
            X = glass[index];
 
            # Keep the amount less
            # than or equal to
            # capacity in current glass
            glass[index] = 1.0 if (X >= 1.0) else X;
 
            # Get the remaining amount
            X = (X - 1) if (X >= 1.0) else 0.0;
 
            # Distribute the remaining
            # amount to the down two glasses
            glass[index + row] += (X / 2);
            glass[index + row + 1] += (X / 2);
            index+=1;
 
    # The index of jth glass
    # in ith row will
    # be i*(i-1)/2 + j - 1
    return glass[int(i * (i - 1) /2 + j - 1)];
 
# Driver Code
if __name__ == "__main__":
     
    i = 2;
    j = 2;
    X = 2.0;
# Total amount of water
 
    res=repr(findWater(i, j, X));
    print("Amount of water in jth glass of ith row is:",res.ljust(8,'0'));
# This Code is contributed by mits


C#




// Program to find the amount
// of water in j-th glass
// of i-th row
using System;
 
class GFG
{
// Returns the amount of water
// in jth glass of ith row
static float findWater(int i, int j,
                       float X)
{
// A row number i has maximum i
// columns. So input column
// number must be less than i
if (j > i)
{
    Console.WriteLine("Incorrect Input");
    Environment.Exit(0);
}
 
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
int ll = (int)Math.Round((double)(i * (i + 1)));
float[] glass = new float[ll + 2];
 
// Put all water in first glass
int index = 0;
glass[index] = X;
 
// 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
for (int row = 1; row <= i ; ++row)
{
    // Fill glasses in a given row.
    // Number of columns in a row
    // is equal to row number
    for (int col = 1;
            col <= row; ++col, ++index)
    {
        // Get the water from current glass
        X = glass[index];
 
        // Keep the amount less than
        // or equal to capacity in
        // current glass
        glass[index] = (X >= 1.0f) ?
                              1.0f : X;
 
        // Get the remaining amount
        X = (X >= 1.0f) ? (X - 1) : 0.0f;
 
        // Distribute the remaining amount
        // to the down two glasses
        glass[index + row] += X / 2;
        glass[index + row + 1] += X / 2;
    }
}
 
// The index of jth glass in ith
// row will be i*(i-1)/2 + j - 1
return glass[(int)(i * (i - 1) /
                   2 + j - 1)];
}
 
// Driver Code
static void Main()
{
    int i = 2, j = 2;
    float X = 2.0f; // Total amount of water
    Console.WriteLine("Amount of water in jth " +
                        "glass of ith row is: " +
                             findWater(i, j, X));
}
}
 
// This code is contributed by mits


PHP




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


Javascript




<script>
 
// Program to find the amount
/// of water in j-th glass
// of i-th row
// Returns the amount of water
// in jth glass of ith row
function findWater(i , j, X)
{
// A row number i has maximum i
// columns. So input column
// number must be less than i
if (j > i)
{
    document.write("Incorrect Input");
}
 
// There will be i*(i+1)/2 glasses
// till ith row (including ith row)
var ll = Math.round((i * (i + 1) ));
glass = Array.from({length: ll+2}, (_, i) => 0.0);
 
// Put all water in first glass
var index = 0;
glass[index] = X;
 
// 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
for (row = 1; row <= i ; ++row)
{
    // Fill glasses in a given row. Number of
    // columns in a row is equal to row number
    for (col = 1;
             col <= row; ++col, ++index)
    {
        // Get the water from current glass
        X = glass[index];
 
        // Keep the amount less than or
        // equal to capacity in current glass
        glass[index] = (X >= 1.0) ? 1.0 : X;
 
        // Get the remaining amount
        X = (X >= 1.0) ? (X - 1) : 0.0;
 
        // Distribute the remaining amount 
        // to the down two glasses
        glass[index + row] += X / 2;
        glass[index + row + 1] += X / 2;
    }
}
 
// The index of jth glass in ith
// row will be i*(i-1)/2 + j - 1
return glass[parseInt((i * (i - 1) /
                   2 + j - 1))];
}
 
// Driver Code
var i = 2, j = 2;
var X = 2.0; // Total amount of water
document.write("Amount of water in jth " +
                     "glass of ith row is: " +
                          findWater(i, j, X));
                           
// This code is contributed by 29AjayKumar
 
</script>


Output: 

Amount of water in jth glass of ith row is: 0.500000

Time Complexity: O(i*(i+1)/2) or O(i^2) 
Auxiliary Space: O(i*(i+1)/2) or O(i^2)

This article is compiled by Rahul and reviewed by GeeksforGeeks team.

Method 2 (Using BFS Traversal)

we will discuss another approach to this problem. First, we add a Triplet(row, col,rem-water) in the queue which indicates the starting value of the first element and fills 1-litre water.  Then we simply apply bfs i.e. and we add left(row+1, col-1,rem-water) Triplet and right(row+1, col+1,rem-water) Triplet into the queue with half of the remaining water in first Triplet and another half into the next Triplet.

Following is the implementation of this solution.

C++




// CPP program for above approach
#include<bits/stdc++.h>
using namespace std;
 
// Program to find the amount 
// of water in j-th glass
// of i-th row
void findWater(float k, int i, int j)
{
     
    // stores how much amount of water
    // present in every glass 
    float dp[i+1][2*i + 1];
    bool vis[i+1][2*i + 1];
     
    // initialize dp and visited arrays
    for(int n=0;n<i+1;n++)
    {
        for(int m=0;m<(2*i+1);m++)
        {
            dp[n][m] = 0;
            vis[n][m] = false;
        }
    }
     
    // store Triplet i.e curr-row , curr-col
    queue<pair<int,int>>q;
    dp[0][i] = k;
     
    // we take the center of the first row for
    // the location of the first glass
    q.push({0,i});
    vis[0][i] = true;
     
    // this while loop runs unless the queue is not empty
    while(!q.empty())
    {
        // First we remove the pair from the queue
        pair<int,int>temp = q.front();
        q.pop();
        int n = temp.first;
        int m = temp.second;
         
         
        // as we know we have  to calculate the
        // amount of water in jth glass
        // of ith row . so first we check if we find solutions
        // for the every glass of i'th row.
        // so, if we have calculated the result
        // then we break the loop
        // and return our answer
        if(i == n)
            break;
             
             
        float x = dp[n][m];
        if(float((x-1.0)/2.0) < 0)
        {
            dp[n+1][m-1] += 0;
            dp[n+1][m+1] += 0;
        }
        else
        {
            dp[n+1][m-1] += float((x-1.0)/2.0);
            dp[n+1][m+1] += float((x-1.0)/2.0);   
        }
        if(vis[n+1][m-1]==false)
        {
            q.push({n+1,m-1});
            vis[n+1][m-1] = true;
        }
        if(vis[n+1][m+1]==false)
        {
            q.push({n+1,m+1});
            vis[n+1][m+1] = true;
        }
    }
    
    if(dp[i-1][2*j-1]>1)
        dp[i-1][2*j-1] = 1.0;
         
    cout<<"Amount of water in jth glass of ith row is: ";
     
    // print the result for jth glass of ith row
    cout<<fixed<<setprecision(6)<<dp[i-1][2*j-1]<<endl;
 
}
 
// Driver Code
int main()
{
     
    //k->water in litres
    float k; 
    cin>>k;
   
    //i->rows  j->cols
    int i,j;
    cin>>i>>j; 
   
    // Function Call 
    findWater(k,i,j);
    return 0;
}
 
 // This code is contributed by Sagar Jangra and Naresh Saharan


Java




// Program to find the amount 
/// of water in j-th glass
// of i-th row
import java.io.*;
import java.util.*;
 
// class Triplet which stores curr row
// curr col and curr rem-water
// of every glass
class Triplet
{
  int row;
  int col;
  double rem_water;
  Triplet(int row,int col,double rem_water)
  {
    this.row=row;this.col=col;this.rem_water=rem_water;
  }
}
 
 
class GFG
{
  // Returns the amount of water
  // in jth glass of ith row
  public static double findWater(int i,int j,int totalWater)
  {
 
    // stores how much amount of water present in every glass  
    double dp[][] = new double[i+1][2*i+1];
 
    // store Triplet i.e curr-row , curr-col, rem-water
    Queue<Triplet> queue = new LinkedList<>();
 
    // we take the center of the first row for
    // the location of the first glass
    queue.add(new Triplet(0,i,totalWater));
 
 
    // this while loop runs unless the queue is not empty
    while(!queue.isEmpty())
    {
      // First we remove the Triplet from the queue
      Triplet curr = queue.remove();
 
      // as we know we have  to calculate the
      // amount of water in jth glass
      // of ith row . so first we check if we find solutions
      // for the every glass of i'th row.
      // so, if we have calculated the result
      // then we break the loop
      // and return our answer
      if(curr.row == i)
        break;
 
      // As we know maximum capacity of every glass
      // is 1 unit. so first we check the capacity
      // of curr glass is full or not.
      if(dp[curr.row][curr.col] != 1.0)
      {
        // calculate the remaining capacity of water for curr glass
        double rem_water = 1-dp[curr.row][curr.col];
 
        // if the remaining capacity of water for curr glass
        // is greater than then the remaining capacity of total
        // water then we put all remaining water into curr glass
        if(rem_water > curr.rem_water)
        {
          dp[curr.row][curr.col] += curr.rem_water;
          curr.rem_water = 0;
        }
        else
        {
          dp[curr.row][curr.col] += rem_water;
          curr.rem_water -= rem_water;
        }
      }
 
      // if remaining capacity of total water is not equal to
      // zero then we add left and right glass of the next row
      // and gives half capacity of total water to both the
      // glass
      if(curr.rem_water != 0)
      {
        queue.add(new Triplet(curr.row + 1,curr.col -
                                  1,curr.rem_water/2.0));
        queue.add(new Triplet(curr.row + 1,curr.col +
                                  1,curr.rem_water/2.0));
      }
    }
 
    // return the result for jth glass of ith row
    return dp[i-1][2*j-1];
  }
 
  // Driver Code
  public static void main (String[] args)
  {
    int i = 2, j = 2;
    int totalWater = 2; // Total amount of water
    System.out.print("Amount of water in jth glass of ith row is:");
    System.out.format("%.6f", findWater(i, j, totalWater));  
  }
 
}
  // this code is contributed by  Naresh Saharan and Sagar Jangra


Python3




# Program to find the amount
# of water in j-th glass of i-th row
 
# class Triplet which stores curr row
# curr col and curr rem-water
# of every glass
class Triplet:
    def __init__(self, row, col, rem_water):
        self.row = row
        self.col = col
        self.rem_water = rem_water
 
# Returns the amount of water
# in jth glass of ith row
def findWater(i, j, totalWater):
   
    # stores how much amount of water present in every glass 
    dp = [[0.0 for i in range(2*i+1)] for j in range(i+1)]
  
    # store Triplet i.e curr-row , curr-col, rem-water
    queue = []
  
    # we take the center of the first row for
    # the location of the first glass
    queue.append(Triplet(0,i,totalWater))
  
    # this while loop runs unless the queue is not empty
    while len(queue) != 0:
      # First we remove the Triplet from the queue
      curr = queue.pop(0)
      # as we know we have  to calculate the
      # amount of water in jth glass
      # of ith row . so first we check if we find solutions
      # for the every glass of i'th row.
      # so, if we have calculated the result
      # then we break the loop
      # and return our answer
      if curr.row == i:
        break
  
      # As we know maximum capacity of every glass
      # is 1 unit. so first we check the capacity
      # of curr glass is full or not.
      if dp[curr.row][curr.col] != 1.0:
         
        # calculate the remaining capacity of water for curr glass
        rem_water = 1-dp[curr.row][curr.col]
  
        # if the remaining capacity of water for curr glass
        # is greater than then the remaining capacity of total
        # water then we put all remaining water into curr glass
        if rem_water > curr.rem_water:
          dp[curr.row][curr.col] += curr.rem_water
          curr.rem_water = 0
        else:
          dp[curr.row][curr.col] += rem_water
          curr.rem_water -= rem_water
  
      # if remaining capacity of total water is not equal to
      # zero then we add left and right glass of the next row
      # and gives half capacity of total water to both the
      # glass
      if curr.rem_water != 0:
        queue.append(Triplet(curr.row + 1,curr.col - 1,(curr.rem_water/2)))
        queue.append(Triplet(curr.row + 1,curr.col + 1,(curr.rem_water/2)))
  
    # return the result for jth glass of ith row
    return dp[i - 1][2 * j - 1]
 
i, j = 2, 2
totalWater = 2 # Total amount of water
print("Amount of water in jth glass of ith row is:", end = "")
print("{0:.6f}".format(findWater(i, j, totalWater)))
 
# This code is contributed by decode2207.


C#




// Program to find the amount
/// of water in j-th glass
using System;
using System.Collections.Generic;
class GFG {
     
    // class Triplet which stores curr row
    // curr col and curr rem-water
    // of every glass
    class Triplet {
        
        public int row, col;
        public double rem_water;
        
        public Triplet(int row, int col, double rem_water)
        {
            this.row = row;
            this.col = col;
            this.rem_water = rem_water;
        }
    }
     
  // Returns the amount of water
  // in jth glass of ith row
  public static double findWater(int i, int j, int totalWater)
  {
  
    // stores how much amount of water present in every glass 
    double[,] dp = new double[i+1,2*i+1];
  
    // store Triplet i.e curr-row , curr-col, rem-water
    List<Triplet> queue = new List<Triplet>();
  
    // we take the center of the first row for
    // the location of the first glass
    queue.Add(new Triplet(0,i,totalWater));
  
  
    // this while loop runs unless the queue is not empty
    while(queue.Count > 0)
    {
      // First we remove the Triplet from the queue
      Triplet curr = queue[0];
      queue.RemoveAt(0);
  
      // as we know we have  to calculate the
      // amount of water in jth glass
      // of ith row . so first we check if we find solutions
      // for the every glass of i'th row.
      // so, if we have calculated the result
      // then we break the loop
      // and return our answer
      if(curr.row == i)
        break;
  
      // As we know maximum capacity of every glass
      // is 1 unit. so first we check the capacity
      // of curr glass is full or not.
      if(dp[curr.row,curr.col] != 1.0)
      {
        // calculate the remaining capacity of water for curr glass
        double rem_water = 1-dp[curr.row,curr.col];
  
        // if the remaining capacity of water for curr glass
        // is greater than then the remaining capacity of total
        // water then we put all remaining water into curr glass
        if(rem_water > curr.rem_water)
        {
          dp[curr.row,curr.col] += curr.rem_water;
          curr.rem_water = 0;
        }
        else
        {
          dp[curr.row,curr.col] += rem_water;
          curr.rem_water -= rem_water;
        }
      }
  
      // if remaining capacity of total water is not equal to
      // zero then we add left and right glass of the next row
      // and gives half capacity of total water to both the
      // glass
      if(curr.rem_water != 0)
      {
        queue.Add(new Triplet(curr.row + 1,curr.col -
                                  1,curr.rem_water/2.0));
        queue.Add(new Triplet(curr.row + 1,curr.col +
                                  1,curr.rem_water/2.0));
      }
    }
  
    // return the result for jth glass of ith row
    return dp[i - 1, 2 * j - 1];
  }
 
  static void Main() {
    int i = 2, j = 2;
    int totalWater = 2; // Total amount of water
    Console.Write("Amount of water in jth glass of ith row is:");
    Console.Write(findWater(i, j, totalWater).ToString("0.000000")); 
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
// Program to find the amount
/// of water in j-th glass
// of i-th row
 
// class Triplet which stores curr row
// curr col and curr rem-water
// of every glass
class Triplet
{
    constructor(row,col,rem_water)
    {
        this.row=row;
        this.col=col;
        this.rem_water=rem_water;
    }
}
 
// Returns the amount of water
  // in jth glass of ith row
function findWater(i,j,totalWater)
{
    // stores how much amount of water present in every glass 
    let dp = new Array(i+1);
    for(let k=0;k<dp.length;k++)
    {
        dp[k]=new Array((2*i)+1);
        for(let l=0;l<dp[k].length;l++)
        {
            dp[k][l]=0;
        }
         
    }
  
    // store Triplet i.e curr-row , curr-col, rem-water
    let queue = [];
  
    // we take the center of the first row for
    // the location of the first glass
    queue.push(new Triplet(0,i,totalWater));
  
    // this while loop runs unless the queue is not empty
    while(queue.length!=0)
    {
      // First we remove the Triplet from the queue
      let curr = queue.shift();
      // as we know we have  to calculate the
      // amount of water in jth glass
      // of ith row . so first we check if we find solutions
      // for the every glass of i'th row.
      // so, if we have calculated the result
      // then we break the loop
      // and return our answer
      if(curr.row == i)
        break;
  
      // As we know maximum capacity of every glass
      // is 1 unit. so first we check the capacity
      // of curr glass is full or not.
      if(dp[curr.row][curr.col] != 1.0)
      {
        // calculate the remaining capacity of water for curr glass
        let rem_water = 1-dp[curr.row][curr.col];
  
        // if the remaining capacity of water for curr glass
        // is greater than then the remaining capacity of total
        // water then we put all remaining water into curr glass
        if(rem_water > curr.rem_water)
        {
          dp[curr.row][curr.col] += curr.rem_water;
          curr.rem_water = 0;
        }
        else
        {
          dp[curr.row][curr.col] += rem_water;
          curr.rem_water -= rem_water;
        }
      }
  
      // if remaining capacity of total water is not equal to
      // zero then we add left and right glass of the next row
      // and gives half capacity of total water to both the
      // glass
      if(curr.rem_water != 0)
      {
        queue.push(new Triplet(curr.row + 1,curr.col -
                                  1,(curr.rem_water/2)));
        queue.push(new Triplet(curr.row + 1,curr.col +
                                  1,(curr.rem_water/2)));
      }
    }
  
    // return the result for jth glass of ith row
    return dp[i-1][2*j-1];
}
 
// Driver Code
let i = 2, j = 2;
let totalWater = 2; // Total amount of water
document.write("Amount of water in jth glass of ith row is:");
document.write(findWater(i, j, totalWater).toFixed(6)); 
 
// This code is contributed by rag2127
</script>


Output

Amount of water in jth glass of ith row is:0.500000

Time Complexity:  O(i^2)
Auxiliary Space:  O(i^2)



Similar Reads

Find amount of water wasted after filling the tank
Given the volume V of a tank in liter. There is a pump which is filling the tank at speed of M liter per minute. There is a leakage at the bottom of the tank which wasting water at speed N liter per minute. Given N is less than M. The task is to calculate how much amount of water will be wasted if leakage is seen after filling the full tank.Example
5 min read
Program to check if water tank overflows when n solid balls are dipped in the water tank
Given the dimensions of cylindrical water tank, spherical solid balls and the amount of water present in the tank check if water tank will overflow when balls are dipped in the water tank. Examples : input : H = 10, r = 5 h = 5 N = 2, R = 2 output : Not in overflow state Explanation : water tank capacity = 3.14 * r * r * H = 3.14 * 5 * 5 * 10 = 785
8 min read
Hour-glass Pattern
Given positive integer n, print numeric pattern in form of an hourglass.Examples : Input : rows_no = 7 Output : 1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7 6 7 5 6 7 4 5 6 7 3 4 5 6 7 2 3 4 5 6 7 1 2 3 4 5 6 7 C/C++ Code // CPP code for hour glass // pattern. #include &lt;iostream&gt; using namespace std; // Function definition void pat
7 min read
Maximum sum of cocktail glass in a 2D matrix
Given a 2D matrix mat[][], the task is to find the maximum sum of a cocktail glass. A Cocktail glass is made of 6 cells in the following form: X X X X X X Examples: Input: mat[][] = { {1, 0, 4, 0, 0}, {0, 3, 0, 0, 0}, {1, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}} Output: 11 Below is the cocktail glass with maximum sum: 1 4 3 1 1 1 Input: mat[]
8 min read
Maximum sum of hour glass in matrix
Given a 2D matrix, the task is to find the maximum sum of an hourglass. An hour glass is made of 7 cells in following form. A B C D E F G Examples: Input : 1 1 1 0 0 0 1 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 Output : 7 Below is the hour glass with maximum sum: 1 1 1 1 1 1 1 Input : 0 3 0 0 0 0 1 0 0 0 1 1 1 0 0 0 0 2 4 4 0 0 0 2 4 Output : 11 Below i
11 min read
Find amount to be added to achieve target ratio in a given mixture
You are given a container of X liters containing a mixture of wine and water. The mixture contains W% of water in it. How many liters of water must be added to increase the ratio of water to Y%? The input includes 3 integers: X, W, and Y respectively. The output should be in float format up to 2 decimal points. Examples: Input : X = 125, W = 20, Y
4 min read
Find the maximum amount that can be collected by selling movie tickets
Given an integer N and an array seats[] where N is the number of people standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the ith row of the movie theater. The task is to find the maximum amount a theater owner can make by selling movie tickets to N people. Price of a ticket is equal to the maximum number of empty
7 min read
Find maximum height to cut all chocolates horizontally such that at least K amount remains
Given an array arr[] consisting of heights of N chocolate bars, the task is to find the maximum height at which the horizontal cut is made to all the chocolates such that the sum remaining amount of chocolate is at least K. Examples: Input: K = 7, arr[] = [15, 20, 8, 17]Output: 15Explanation:Suppose a cut is made at height 8:-&gt; chocolate taken f
10 min read
Find out the minimum number of coins required to pay total amount
Given a total amount of N and unlimited number of coins worth 1, 10 and 25 currency coins. Find out the minimum number of coins you need to use to pay exactly amount N.Examples: Input : N = 14Output : 5You will use one coin of value 10 and four coins of value 1.Input : N = 88Output : 7 Approach: To solve this problem we will use recursion to try al
11 min read
Find the minimum and maximum amount to buy all N candies
In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided. There is also an attractive offer by the candy store. We can buy a single candy from the store and get at most K other candies (all are different types) for free. Find the minimum amount of money we have to spend t
11 min read
three90RightbarBannerImg