AlgoViz

Pattern 9

Easy

Star diamond

Problem

Print a star diamond (pyramid + inverted pyramid) 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

A diamond is simply the pyramid printed, then the inverted pyramid printed underneath. Once you have both loops written, composition does the work — no new formula is needed.

The trick

  • Two independent loops, stacked. Do not try to do it in one.
rows10

Step 1 of 12. Diamond: a pyramid on top, its mirror below. rows 10.

1/12
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2//     *3//    ***4//   *****5//  *******6// *********7// *********8//  *******9//   *****10//    ***11//     *12 13for i in 1..2n:14  k = i <= n ? i : 2n - i + 115  print ' ' x (n-k)16  print '*' x (2k-1)17  newline

Input

grid
10 × 9

Memory

rows
10

Output

printed rows
rows
10

Check yourself

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

Example

Input:
n = 5
Output:
★ / ★ ★ ★ / ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ ★ ★ / ★ ★ ★ ★ ★ / ★ ★ ★ / ★

Finished the walkthrough? Add it to your streak.