Find the amount of water in ith cup in a pyramid structure?

后端 未结 6 1576
猫巷女王i
猫巷女王i 2020-12-15 12:12

This question was asked in a forum. Any suggestions?

There is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on.. It looks something like this

6条回答
  •  醉酒成梦
    2020-12-15 12:58

    Here is a simple and comprehensible implementation:

    public class main {
        static float total_water = 50;
        static int N = 20;
        static glass[][] pyramid = new glass[N][N];
    
        public static void main(String[] args) {
            build_pyramid();
            pour_water(0, 0, total_water);
            print_pyramid();
            print_total_water_stored();
        }
    
        private static void print_total_water_stored() {
            float total = 0;
            for (int i = 0; i < N; i++) {
                for (int j = 0; j <= i; j++)
                    total += pyramid[i][j].filled;
            }
            System.out.println("total water stored= " + total);
        }
    
        private static void pour_water(int row, int col, float water) {
            if (water >= (pyramid[row][col].capacity - pyramid[row][col].filled)) {
                water -= (pyramid[row][col].capacity - pyramid[row][col].filled);
                pyramid[row][col].filled = pyramid[row][col].capacity;
                pour_water(row + 1, col, water / 2);
                pour_water(row + 1, col + 1, water / 2);
            } else {
                pyramid[row][col].filled += water;
            }
        }
    
        public static void build_pyramid() {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++)
                    pyramid[i][j] = new glass(1);
            }
        }
    
        public static void print_pyramid() {
            for (int i = 0; i < N; i++) {
                for (int j = 0; j <= i; j++)
                    System.out.print(pyramid[i][j].filled + " ");
                System.out.println();
            }
        }
    }
    
    class glass {
        float capacity;
        float filled;
    
        glass(float cap) {
            capacity = cap;
            filled = 0;
        }
    }
    

提交回复
热议问题