AlgoViz

Pattern 20

Medium

Star butterfly, opening outward

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

The same butterfly with the gap running the other way — narrow at the ends, wide in the middle. Deriving the gap from the row index is again the whole exercise.

The trick

  • The two halves are always equal, so compute one and mirror it.
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 13order = [1..n] ++ [n..1]14for k in order:15  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.