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;
}