AlgoViz

Pattern 17

Easy

Alphabet hill A, ABA, ABCBA

Problem

Print an alphabet hill A, ABA, ABCBA, … 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 centred pyramid whose letters climb to the row's peak and back down. Compute the distance from the centre and let that pick the letter, which avoids writing the ascending and descending halves separately.

The trick

  • Letter = 'A' + (distance from the row's centre subtracted from the peak).
  • Rows are 2i-1 wide, so the centre of row i is at offset i-1.
rows5

Step 1 of 7. Alphabet hill: climb A..letter, then back down. rows 5.

1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2//     A3//    A B A4//   A B C B A5//  A B C D C B A6// A B C D E D C B A7 8for i in 1..n:9  print ' ' x (n-i)10  up: A..char('A'+i-1); down: back to A

Input

grid
5 × 9

Memory

rows
5

Output

printed rows
rows
5

Check yourself

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

Example

Input:
n = 5
Output:
A / A B A / A B C B A / A B C D C B A / A B C D E D C B A

Finished the walkthrough? Add it to your streak.