3 ms·
Actually, if your M/2 isn't integer division (which I assume is the case from your use of ceil around it first), your 5x5 pyramid would look like this: 234
by SmallDeadGuy 9y ago
Actually, if your M/2 isn't integer division (which I assume is the case from your use of ceil around it first), your 5x5 pyramid would look like this:
23443
34554
45665
45665
34554
Using max_height - (abs(i - floor(M/2)) + abs(j - floor(N/2))) would give the properly-centered pyramid:
23432
34543
45654
34543
23432
Your max height should really be just max(ceil(M/2), ceil(N/2)) for a height of 3 going to 1 at the edges or floor(M/2) for 2 to 0. Using both Manhattan distances gives you an octagon-base pyramid (approximated to the square shape) when really you just want the max of both distances:
max_height - max(abs(i - floor(M/2)), abs(j - floor(N/2)))
gives:
11111
12221
12321
12221
11111
But this only works for square pyramids, using 3x5 you get:
12221
12321
12221
If you want a rectangle pyramid, use min manhattan distance from edge (don't need a max height then):
1 + min(i, N-i-1, j, M-j-1)
gives:
11111
12221
11111
or for a 7x10 grid:
1111111111
1222222221
1233333321
1234444321
1233333321
1222222221
1111111111
Python 3 code for those who want to test themselves:
N = 7
M = 10
for i in range(N):
print("".join(str(1 + min(i,j,N-i-1,M-j-1)) for j in range(M)))
- IIAOPSW 9y agoThis is what I get for trying to work it out in my head and be the first clever person to respond to OP. I like your code. very elegant solution with mins and such.