AlgoViz

Pattern 19

Easy

Star butterfly

Problem

Print a star butterfly 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

Two mirrored blocks of stars with a gap between them that widens then narrows. Print the top half, then the bottom half; the only formula is the gap width.

The trick

  • Top row i: i stars, 2(n-i) spaces, i stars.
rows10

Step 1 of 12. Butterfly: two triangles grow to the middle, then shrink. 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 k16  print ' ' x 2(n-k)17  print '*' x k18  newline

Input

grid
10 × 10

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.