4
\$\begingroup\$

This question already has an answer here:

A zigzag scan is a method of encoding 2D information in one dimension:

Zigzag scan

Write a function or program that, given a one-dimensional string of printable ASCII characters, will reverse the zigzag scan to arrange its characters into a square.

For example, given the input string ABeIfCDgJmnKhLop, your program should return:

ABCD
efgh
IJKL
mnop

Here it is with the zigzag illustrated. The green line shows the order of the original characters, starting at the top left:

ABCD\nefgh\nIJKL\nmnop

The side length 𝒔 of the output (i.e. the number of rows and columns) for an input string of length 𝒏 must equal ⌈√𝒏̅⌉ (ceil(sqrt(n))). The zigzag pattern is slightly different for even and odd values of 𝒔. Note how to upper right corner of the zigzag in the below example (𝒔 = 5) differs from the above (𝒔 = 4).

Given the string Woamnlfgasa d gAeMrtouz, your output should be:

Wolfg
ang A
madeu
s Moz
art

That is:

Wolfg\nang A\nmadeu\ns Moz\nart

Winning

This is . The solution with the fewest bytes win.

Rules

Input must be taken as a single string or list of characters. It may not have any extra whitespace, but for a single trailing newline. The input (sans newline) will have length 1 ≤ 𝒏 ≤ 4,096.

Output must be a string with multiple lines, a list of strings, or a list of lists of characters. Trailing whitespace (any amount) on each line is allowed but optional, as is a single trailing newline.

Standard loopholes are forbidden.

Test cases

The below test cases are formatted as:

Input

Output
...
$

$
PPCG

PP
CG
foobarbaz

for
oab
baz
Ooo...    ...ooO

Oo. 
o. .
. .o
 .oO
OOo.oOOo.oOo.oOo.oOOo.oOO

OOOOO
ooooo
.....
ooooo
OOOOO
PrmPmogiusC znragzaooldnl edef   G

Progra 
mming  
Puzzle 
s and  
Code G 
olf
The quick brown fox jumps over the lazy dog

Thuin v
eqcwfoe
 koo ry
 rxs z 
b ptad
jmhlo
ue g
\$\endgroup\$

marked as duplicate by AdmBorkBork code-golf Jan 5 '18 at 15:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • \$\begingroup\$ Sandbox post \$\endgroup\$ – Jordan Jan 5 '18 at 15:39
  • \$\begingroup\$ Related \$\endgroup\$ – Jordan Jan 5 '18 at 15:39
  • \$\begingroup\$ Related. (The opposite conversion and on matrices instead of strings.) \$\endgroup\$ – Martin Ender Jan 5 '18 at 15:42
  • 1
    \$\begingroup\$ @MartinEnder Oh for heaven's sake. I searched for ages. Apparently the keyword I was missing was "zigzagify." In fact, this other challenge of yours (the reverse operation) is pretty much a duplicate. I really wish this had come up in the sandbox. \$\endgroup\$ – Jordan Jan 5 '18 at 15:45
  • \$\begingroup\$ Oh, I completely forgot that I did both directions of this conversion... in that case yes, that's a very close match. \$\endgroup\$ – Martin Ender Jan 5 '18 at 15:46

Browse other questions tagged or ask your own question.