AlgoViz

Pattern 12

Easy

Number crown with a gap

Problem

Print a number crown: 1..i, a gap, then i..1 for a given size n.

In simple words

Use one loop for the rows and another for what goes in each row to draw the shape.

The idea

Three inner loops per row: count up 1..i, print the shrinking gap of spaces, then count back down i..1. The gap is 2(n-i) wide, which keeps the two halves pushed to the outer edges.

The trick

  • Spaces between the halves = 2(n - i).
rows4

Step 1 of 6. Number crown: 1..i, a gap, then i..1. rows 4.

1/6
Optimal
timeO(n^2)spaceO(1)
1// n = 4 produces:2// 1      13// 12    214// 123  3215// 123443216 7for i in 1..n:8  print 1..i9  print ' ' x 2(n-i)10  print i..1

Input

grid
4 × 8

Memory

rows
4

Output

printed rows
rows
4

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
n = 4
Output:
1 1 / 1 2 2 1 / 1 2 3 3 2 1 / 1 2 3 4 4 3 2 1

Finished the walkthrough? Add it to your streak.