All problems

Problem 64

Zigzag Conversion

Medium · 20 pts · String, Simulation

Problem

Write the string S in a zigzag pattern on R rows: put the first character in row 1, the next in row 2, and so on down to row R, then go back up diagonally through rows R - 1, ..., 2, then down again, and keep repeating. Finally read the rows from top to bottom, each row from left to right, and print the resulting string. You do not need to draw the grid. Keep a list of R strings and a current row with a direction, and append each character to its row, reversing direction at the top and bottom rows. If R is 1, the string does not change.

Input

First line: string S (letters). Second line: integer R.

Output

Print the string read row by row.

Constraints

1 <= |S| <= 1000; 1 <= R <= 1000

Example input

PAYPALISHIRING
3

Example output

PAHNAPLSIIGYIR

Explanation

Writing "PAYPALISHIRING" in a zigzag on 3 rows puts P A H N in the first row, A P L S I I G in the second and Y I R in the third. Reading the rows in order gives PAHNAPLSIIGYIR.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Integer to Roman Next: Longest Repeating Character Replacement