0

I'm learning java and wanted to do this problem:

Build a pyramid from given input list of integer values. Numbers are to be sorted ascending from top to bottom, from left to right.

Empty spaces are to be filled with zeros. In order to make the pyramid symmetric input numbers should alternate with zeros.

For example, for input A={2, 4, 3, 5, 6, 1} the pyramid will look like:

  • [0,0,1,0,0]
    [0,2,0,3,0]
    [4,0,5,0,6]

I've written some code but the problem is that the solution comes out something like:

  • [0,1,2]
    [0,1,2]

Instead it should be something like this:

  • [0,1,0]
    [1,2,2]

Now I get an Array out of index error, what can I change?

public int[][] buildPyramid(List<Integer> inputNumbers) 
    throws CannotBuildPyramidException {

    // Calculate the number of rows in the pyramid
    int rows = (int) (Math.sqrt(inputNumbers.size() * 2) - 1);

    // Initialize the 2D array that will hold the pyramid
    int[][] pyramid = new int[rows][rows];

    // Initialize the variables that will help us navigate through the pyramid
    int row = 0;
    int col = rows / 2;
    boolean isDown = true;

    // Iterate through the list of numbers and build the pyramid
    for (int num : inputNumbers) {
        pyramid[row][col] = num;

        if (isDown) {
            row++;
        } else {
            row--;
            col--;
        }

        if (row == rows) {
            row = rows - 2;
            col++;
            isDown = false;
        } else if (row < 0) {
            row = 1;
            isDown = true;
        }
    }

    // Print the pyramid
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < rows; j++) {
            if (pyramid[i][j] == 0) {
                System.out.print("0 ");
            } else {
                System.out.print(pyramid[i][j] + " ");
            }
        }
        System.out.println();
    }
    return pyramid;
}
Steve Piercy
  • 13,693
  • 1
  • 44
  • 57
  • what is the input that expected output is `[0,1,0] [1,2,2]`? why would value 1 be present in two different rows of the pyramid? – Sharon Ben Asher Dec 21 '22 at 10:43
  • It's an example what I want is to sort the list and then creat a pyramid were the first number at the top is the smallest of the list and in the second row the next two and so on – Omar Russo Castillo Dec 21 '22 at 10:47
  • 2
    if you want help, you need to give complete example: input, expected output and actual. also, if you get error, it tells you the source line number – Sharon Ben Asher Dec 21 '22 at 11:01

0 Answers0