# A square of text

## The Challenge

Given a string, output the text in the shape of a square.

You can assume that the text will always fit in a square, and that it will never be an empty string.

You can also assume it will never have newlines.

### Example

Input:
Hi, world

Output:
Hi,
wo
rld


## Test Cases

Input:
Hi, world! Hello

Output:
Hi,
worl
d! H
ello

Input:
Lorem ipsum dolor sit amt

Output:
Lorem
ipsu
m dol
or si
t amt

Input:
H

Output:
H


## Rules

• This is , so shortest answer in bytes wins! Tiebreaker is most upvoted answer.
• Standard loopholes are forbidden.
• Can we assume that the input will never have new lines? – MayorMonty Aug 6 '16 at 2:13
• @MayorMonty yep. – acrolith Aug 6 '16 at 2:20
• Can we output array of strings instead? – Leaky Nun Aug 6 '16 at 5:10
• @LeakyNun no 15 chars – acrolith Aug 6 '16 at 16:58
• May we print with a trailing newline? – Giuseppe Oct 4 '17 at 15:53

## Matlab, 28 bytes

@(s)reshape(s,nnz(s)^.5,[])'


reshape puts output in columns first, so we have to transpose the whole thing to get the desired output.

# PHP, 47 bytes

<?=chunk_split($a=$argv[1],strlen($a)**.5," ");  For multibyte strings, 66 bytes <?=preg_replace("/.{1,".sqrt(strlen($a=$argv[1]))."}/u","$0
t=SQR(len(i$)) FOR x=0TO t-1 ?MID$(i$,x*t+1,t) NEXT  # q/kdb+, 25 22 bytes Solution: -1{(2#6h$sqrt(#)x)#x};


Example:

q)-1{(2#6h$sqrt(#)x)#x}"Lorem ipsum dolor sit amt"; Lorem ipsu m dol or si t amt  Explanation: -1{(2#6h$sqrt count x)#x}; / ungolfed solution
{                     }  / lambda function
#x   / take from x (input)
(                 )     / do everything in the brackets first
count x      / length of x
sqrt              / calculate square-root
6h$/ cast to integer 2# / duplicate this number, e.g. 5->(5;5) -1 ; / print to stdout  # SOGL V0.12, 1 byte √  Try it Here! - this expects the input on the stack as a function, so there it's called as a function F and then, in the next line, , pushes the input and F executes the function. ### without builtins, 3 bytes l√n  Try it Here! push length, square root it, split input into strings of that length, implicitly output joined with newlines # Perl 6, 28 27 bytes -1 byte thanks to nwellnhof {.comb(.comb**.5+|0)>>.say}  Try it online! • **.5 (or **½) is one byter shorter than .sqrt. – nwellnhof Oct 14 '18 at 11:35 • @nwellnhof I always forget about that! Wouldn't it be nice if we could use the √ symbol instead? – Jo King Oct 14 '18 at 13:06 # Momema, 99 bytes 03i00+1*0*0*-9i=+1**00+-4*0q00+*0-+1+*1*1 1+1*1q=*02*1o03*1p0-9*+4*00+1*03+-1*3p=*3 2+-1*2-9 10o=*2  Try it online! # Explanation  # -- Read the input onto the tape. # -- Set aside the first 4 cells as variables. 0 3 # p = 3 i 0 # do { 0 +1*0 # p = p+1 *0 *-9 # tape[p] = getchar() i =+1**0 # } while (tape[p] != -1) 0 +-4*0 # p = p - 4 # -- Calculate the square root of the input length. q 0 # do { 0 +*0-+1+*1*1 # p = p - (1 + r + r) 1 +1*1 # r = r + 1 q =*0 # } while (p) # -- Print the formatted output. 2 *1 # i = r o 0 # do { 3 *1 # j = r p 0 # do { -9 *+4*0 # putchar(tape[p + 4]) 0 +1*0 # p = p + 1 3 +-1*3 # j = j - 1 p =*3 # } while (j) 2 +-1*2 # i = i - 1 -9 10 # putchar(10) o =*2 # } while (i)  ## Python 3.8, 68 bytes a=int(len(s:=input())**.5) for i in range(0,a**2,a):print(s[i:][:a])  Not the shortest Python answer, but also not the longest. Goes through the string by intervals of the square root of the length of the string. I saved a byte by using Python 3.8's new-fangled assignment expressions. # Kotlin, 57 bytes fun String.s()=chunked(sqrt(length+.0).toInt(),::println)  Explanation: fun String.s()= # Extension method on the string, so we can avoid declaring a param chunked # Actually this method does all the heavy lifting, it splits the string into a list of size N strings (sqrt(length+.0) # Kotlin's sqrt only takes double and produces double :/ .toInt(), # So we need to cast the result for chunked in an ugly way :/ ::println) # But hey, applying a transform to print is actually included for free!  # Python 3, 78 bytes def f(s): r=int(len(s)**.5) return'\n'.join([s[i*r:i*r+r]for i in range(r)])  Try it online! # Stax, 3 bytes :Jm  Run and debug it at staxlang.xyz! Very simple. :J squarifies an array. That m is necessary because Stax will print a list of strings on one line. ### Without the builtin, six bytes c%|q/m  Run and debug it at staxlang.xyz! Copy the string (c) and take its length (%). Square root that length (|q), and split the string into substrings of that (square-rooted) length (/). # K (ngn/k), 11 bytes {(2#%#x)#x}  Try it online! the bracketed expression returns list 5 5 for input "Lorem ipsum dolor sit amt". it reads "2 take sqrt count x", where x is the string argument. then (5 5)#x means "cut x into 5 lists each of length 5". with this we get:  {(2#%#x)#x}"Lorem ipsum dolor sit amt" ("Lorem";" ipsu";"m dol";"or si";"t amt")  # Zsh, 54 51 bytes -3 by ^= instead of =0^(). ((n=$#1,l^=n**0.5))
eval '<<<${1:'{0..$n..$l}':$l}'


Shoutouts to eval jank.

((n=$#1,l^=n**0.5)) # the xor with 0 casts n**0.5 to an integer eval '<<<${1:'           ':$l}' # when eval'd, prints a subtring of length l {0..$n..$l} # brace expansion: {0..4..16} => 0 4 8 12 16  I left in set -x in the TIO link, scroll down to the debug section to see exactly what happens with the brace expansion. ## ListSharp, 157 bytes STRG a=READ[<here>+"\\a.txt"] NUMB b=(int)Math.Sqrt(a LENGTH) [FOREACH NUMB IN 0 TO b-1 AS x] { STRG t=GETRANGE a FROM [x*b+1] TO [x*b+b] ROWS f=f+t } SHOW=f  reads text from local file a.txt , im using embedded c# code and other tricks to make this work. feel free to ask me questions about this code or listsharp in general # C, 64 bytes f(s,m,k){for(m=k=sqrt(strlen(s));k--;s+=m)printf("%.*s\n",m,s);}  Inspired by the other C answer. Only works on platforms where int has the same size as char* (e.g. 32-bit Windows). # Lua, 68 Bytes o=io.read()for s in o:gmatch(("."):rep(math.sqrt(#o)))do print(s)end  Simple and dirty, just how I like it. I use o=io.read() instead of function(o) Which works out as the same length, to save from having to add an extra "end" at the end. Pretty simple in functionality, it just uses gmatch to loop through the string in chunks of math.sqrt(#o), Which is the square root of the length of the string. Sadly, Lua patterns don't offer the regex functionality of {} to denote a specific count, so I had to do :rep() instead. # Racket 102 bytes (λ(s)(let*((l(string-length s))(q(sqrt l)))(for((i(range 0 l q)))(displayln(substring s i(+ i q))))))  More readable form: (define (f s) (let* ((l (string-length s)) (q (sqrt l))) (for((i(range 0 l q))) (displayln (substring s i(+ i q))))))  Testing: (f "Lorem ipsum dolor sit amt") Lorem ipsu m dol or si t amt  # Silicon (non-competing), 6 bytes I added some commands right after I noticed this challenge, so non-competing. iLqnåê  Explanation: iLqnåê i Input q Square root of... L Length n Convert to integer å Split into chunks of n ê Join at newlines  # ISOLADOS (non-competing), 93 bytes ISOLAAAADOS ISOLAAAAAADOS ISOLAAAAAAAADOOS ISOLAAADOOOOOOS ISOLAAAAAAAADOOOS ISOLAAAAAAAAADOS  ISOLAAAADOS input ISOLAAAAAADOS duplicate ISOLAAAAAAAADOOS length ISOLAAADOOOOOOS square root ISOLAAAAAAAADOOOS a split into chunks of length b ISOLAAAAAAAAADOS join by new lines  ## QBIC, 41 bytes ;c=sqr(len(A))[1,c|?mid$$|(A,q,c) q=c*a+1  Unfortunately, it doesn't work on text parameters with spaces in it. I'll put it on the QBIC todo-list. Explanation: ; gets the input as string A sqr(len(A)) calls the QBasic square root function, with the length of A as argument [1,c... Loops from 1 to the height of the square ?mid$$|(..) Prints the middel part of A$. The '$' has a reserved meaning in QBIC and needs to be escaped q=c*a+1 Sets the starting point of the next mid$
<implicit>  NEXT


Note that a more modern version of QBIC can solve this in 27 bytes:

_L;|g=sqr(a)[1,a,g|?_sA,b,g


Improvements are: inline cmd-arg-grabbing (;), implementation of len (_L or _l) and substring (_s). Also, I've improved conditions and workings of the FOR-loop itself.

# K (oK), 14 bytes

Solution:

0:#[2#%#x]x:;


Try it online!

Example:

0:#[2#%#x]x:"Lorem ipsum dolor sit amt";
Lorem
ipsu
m dol
or si
t amt


Explanation:

Similar to my q/kdb+ solution, but a little shorter. Use # to reshape string into a square:

0:#[2#%#x]x:; / the solution
0:          ; / print to stdout and swallow return value
x:  / save input as x
#[     ]    / reshape
#x     / count x
%       / sqrt
2#        / duplicate


# Ly, 31 bytes

irysp>l12/^s<[ol,s!['
o>s<1$]p]  Try it online! Try a square version online, for fun # JavaScript (Node.js), 54 bytes s=>[...s].map((c,i)=>++i%s.length**.5?c:c+\n).join  Try it online! # Python 3, 76 bytes I understand the length of my answer, but I didn't want to copy off the other people that did python, so I took the bit longer route (by like an extra 20 some bytes). i=input() for c in range(len(i)):print(i[c],end="\n"*((c+1)%len(i)**0.5==0))  Try it online! So rather than cut my string after I use the part I want, I keep printing characters until I get to the edge of the square, then I add a newline and keep spewing characters and doing that till we get to the end. # C#, 151 Bytes static string T(string c){string s="";int a=(int)Math.Sqrt(c.Length);for(int i=0;i<c.Length;i++){s=s+c.Substring(0,a)+"\n";c=c.Remove(0,a);}return s;}  # Japt-R, 4 bytes òUÊq  Try it online! ## Explanation: òUÊq ò // Split the input into slices of length: q // Square root of UÊ // Length of the input -R // Join with newlines  # Japt-R, 76 4 bytes òUÊ¬  Try it òUÊ¬ :Implicit input of string U ò :Partition into chunks of length UÊ : Length of U ¬ : Square root :Implicitly join with newlines and output  ## TI-Basic, 33 Bytes Input Str1 length(Str1→Z For(X,1,Z,√(Z Disp sub(Str1,X,√(Z End  This is not a particularly interesting answer, due to the limitations of TI-Basic, but I like the language too much to resist. Note that TI-Basic is tokenized, so byte count for the program is not the same as character count. # Lua, 65 bytes t=io.read()for i in t:gmatch(('.'):rep((#t)^0.5)) do print(i) end  Try it online! Explanation: t=io.read() -- Read input string for i in -- Iterator-based loop t:gmatch( -- over results of pattern-matching on input ('.'):rep( -- Make string of dots (#t)^0.5) -- square root from input length string long ) -- …which is a pattern for matching that long substring ) do -- Loop body print(i) -- Print our match and newline end  TL;DR: it uses pattern-matching (Lua version of regexp) to get square root of input long substrings and prints them. # Lua, 84 bytes (with UTF-8 support) t=io.read()for i in t:gmatch(('.[\128-\191]*'):rep(utf8.len(t)^0.5)) do print(i) end  Try it online! Same idea as above, but with few UTF-8 tricks. # Runic Enchantments, 19 bytes qA,r\;>i:l͍'$ka\$L


Try it online!

Outputs with a trailing newline because its cheaper to loop and wait for stack underflow to cause program termination than to figure out if anything's left on the stack to print. As such the required terminator ; goes unexecuted.

Inputs that are not capable of being square are output as tall rectangles, as computation required to coerce a square through trailing spaces aren't necessary due to challenge spec regarding inputs.

Additionally, spaces need to be escaped in order for the input to be treated as a single string (rather than multiple space-separated strings).