Dynamic Programming 14
There is a stack of water glasses in a form of pascal triangle and a person wants to pour the water at the topmost glass, but the capacity of each glass is 1 unit. Overflow takes place in such a way that after 1 unit, 1/2 of remaining unit gets into bottom left glass and other half in bottom right glass.Now John pours K units of water in the topmost glass and wants to know how much water is there in the Cth glass of the Rth row.
Problem link :- click here
Code
import java.util.Arrays;
import java.util.Scanner;
public class DynamicProgramming_14
{
static void fill(float k, int r, int c, float pyramid[][])
{
if(r >= pyramid.length)
return;
pyramid[r][c] += k;
float rem = 0;
if(pyramid[r][c] > 1)
{
rem = pyramid[r][c] - 1;
pyramid[r][c] = 1;
fill(rem/2, r+1, c, pyramid);
fill(rem/2, r+1, c+1, pyramid);
}
}
static float quantityOfGlass(float k, int row, int col)
{
float pyramid[][] = new float[row+1][row+1];
for(float[] x: pyramid)
Arrays.fill(x, 0);
fill(k, 1, 1, pyramid);
for(int i=1; i<=row; i++)
{
for(int l=1; l<=row-i; l++)
System.out.print("\t");
for(int j=1; j<=i; j++)
{
System.out.print(pyramid[i][j] + "\t\t");
}
System.out.println("\n");
}
return pyramid[row][col];
}
static float quantityOfGlass1(float k, int row, int col)
{
float[][] pyramid = new float[row+1][row+1];
pyramid[1][1] = k;
for(int i=1; i<=row; i++)
{
for(int j=1; j<=i; j++)
if(pyramid[i][j] > 1)
{
float rem = pyramid[i][j] - 1;
pyramid[i][j] = 1;
if(i < row)
{
pyramid[i+1][j] += rem/2;
pyramid[i+1][j+1] += rem/2;
}
}
}
for(int i=1; i<=row; i++)
{
for(int l=1; l<=row-i; l++)
System.out.print("\t");
for(int j=1; j<=i; j++)
{
System.out.print(pyramid[i][j] + "\t\t");
}
System.out.println("\n");
}
return pyramid[row][col];
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the unit of water poured : ");
float k = s.nextFloat();
System.out.print("Enter the row number : ");
int row = s.nextInt();
System.out.print("Enter the glass number : ");
int col = s.nextInt();
float ans = quantityOfGlass1(k, row, col);
System.out.println("\n\n" + ans);
s.close();
}
}
Comments
Post a Comment