Devise an algorithm to draw the following squares when N = 0, 1, 2, 3, 4, 5. Then generate your algorithm by observing the pattern:
n = 5:
rbrrbr
rrbrr
brrb
rbr
rr
b
n = 4:
rrbrr
brrb
rbr
rr
b
n = 0:
b
We notice that the pattern follows a diagonal coloring approach. If y%3 == 0 then we start at x = 0 and color every 3 blocks. If y%3 == 1 then we start at x = 2 and color every 3 blocks. if y%3==2 then we start at x = 1 and color every 3 blocks.
# the offset of the first blue box from x
# if x == 0, and y == 0 -> blue
# if y == 1 or y == 3 or ... (y % 3 == 1) -> 2 red blocks first, then first blue
# if y == 2 or y == 4 or ... (y % 3 == 2) -> 1 red block first, then first blue
def get_offset(y_):
ret_ = {0: 0, 1: 2, 2: 1}
return ret_[y_ % 3]
if __name__ == '__main__':
n = 4
# loop backwards
# the example shows 6x6 for n = 5, so we need -1 on outer loop and y + 1 on inner loop
for y in range(n, -1, -1):
b_offset = get_offset(y)
for x in range(0, y+1):
if x % 3 == b_offset:
print('b', end='')
else:
print('r', end='')
print()