Program to find amount of water in a given glass

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 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 top glass, how much water will be contained by jth glass in ith row?

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

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 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 ith row. There will be i*(i+1)/2 glasses till ith row.

class Solution {
    public 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)
            return -1;
        // There will be i*(i+1)/2 glasses till ith row (including ith row)
        int glasses = (i * (i + 1)) / 2;
        float[] glass = new float[glasses + 1];
        // Put all water in first glass
        glass[1] = X;
        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++) {
                // Get the water from current glass
                float current = glass[row + col - 1];
                // Keep the amount less than or equal to capacity in current glass
                glass[row + col - 1] = (current >= row + col - 1) ? row + col - 1 : current;
                // Get the remaining amount
                current = (current >= row + col - 1) ? (current - (row + col - 1)) : 0;
                // Distribute the remaining amount to the down two glasses
                if (row != i) {
                    glass[(row + col - 1) + row] += current / 2;
                    glass[(row + col - 1) + row + 1] += current / 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))];
    }
}

Last updated