Sunday, September 24th

 Champagne

Given a pyramid of champagne glasses and an amount poured into the top glass, determine how much champagne will be in a given glass in the pyramid

This problem can be solved in a straightforward manner, where, for a given pour we will determine the amount of champagne in every glass in the pyramid , then return the results for the given glasses.  There are only 100 rows total so it is feasible.

To begin, we initialize a 2D-array which will represent the pyramid.  We also add the total amount poured to the top glass

double champagneTower(int poured, int query_row, int query_glass) {
     vector<vector<double> > res(101, vector<double>(101, 0.00));
res[0][0] = poured;
        ..
    }

Then we iterate from the first row down, and by the left glass to the right glass

for (int i = 0; i < 100; i++) {
for (int i = 0; i < 100; i++) {
            ...
           }  
    }

If for a given glass, the value of the glass is more than 1, then we calculate the amount of champagne spilled over to the 2 glasses below it.  Then we set the amount in the original glass to 1

    if (res[i][j] >= 1) {
res[i + 1][j] += (res[i][j] - 1) / 2.0;
res[i + 1][j + 1] += (res[i][j] - 1) / 2.0;
    res[i][j] = 1;
}

Now that we have calculated the champagne in every glass, we return the answer for the given row and glass

double champagneTower(int poured, int query_row, int query_glass) {
     ...
        return res[query_row][query_glass];
    }

A little tricky problem since this straightforward approach isn't used too often.  Calculating all values and the returning the one doesn't seem intuitive to start.  Also, the structure of the problem kind of seems like Pascal's triangle which would call for dynamic programming.  

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th