Editorial for Hollow Pyramid
Problem of the Week 1b
Published in
2 min readNov 3, 2019
The problem statement:
A hollow pyramid is a pyramid with walls and an empty space in it. Your friend James wants to know how a hollow pyramid will look like when cut from the top to bottom. Can you help him out?
This problem tests your understanding of loops. Let’s look at an example. If our input is 5, we can develop a table that looks like our output.
+---+---+---+---+---+---+---+---+---+
| | | | | * | | | | |
+---+---+---+---+---+---+---+---+---+
| | | | * | | * | | | |
+---+---+---+---+---+---+---+---+---+
| | | * | | | | * | | |
+---+---+---+---+---+---+---+---+---+
| | * | | | | | | * | |
+---+---+---+---+---+---+---+---+---+
| * | | * | | * | | * | | * |
+---+---+---+---+---+---+---+---+---+
From the table above, we can make some observations:
- A cell that doesn’t have an asterisk has space.
- The first line has 4 spaces before the first asterisk, the second has 3, the third has 2, the fourth has 1 and the last has none. We can draw some conclusions from here that is the input is n, we first print n-1 spaces on the first line, n-2 spaces on the second, … , n-n spaces on the last line.
- For each row, after we print out an asterisk, we print a space too. Subsequently, we print spaces in pairs until we print the last asterisk for the row.
After these observations, we can write our code. The pseudocode is provided below:
input n
spaces = n - 1 //Number of spaces to print before the first asterisk
for row = 1 to n
//Print spaces
for i = 1 to spaces
print " "
end for
for i = 1 to row
if (row = n)
//Print only asterisks on the last line
print "* "
else if (i = 1 || i = row)
//Print an asterisk at both ends
print "* "
else
//Print spaces in between asterisks
print " "
end if
end for
end for
Do you have another approach to the problem, feel free to share your approach in the comments below. 😃