30
\$\begingroup\$

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.
\$\endgroup\$
7
  • \$\begingroup\$ Can we assume that the input will never have new lines? \$\endgroup\$
    – bren
    Aug 6, 2016 at 2:13
  • \$\begingroup\$ @MayorMonty yep. \$\endgroup\$
    – acrolith
    Aug 6, 2016 at 2:20
  • 2
    \$\begingroup\$ Can we output array of strings instead? \$\endgroup\$
    – Leaky Nun
    Aug 6, 2016 at 5:10
  • \$\begingroup\$ @LeakyNun no 15 chars \$\endgroup\$
    – acrolith
    Aug 6, 2016 at 16:58
  • 2
    \$\begingroup\$ May we print with a trailing newline? \$\endgroup\$
    – Giuseppe
    Oct 4, 2017 at 15:53

70 Answers 70

2
\$\begingroup\$

Risky, 14 bytes

2_2+_2+__1+_1*__?*_1/}!?*_1

Try it online!

Explanation

So many no-ops... 0__0

Parse tree:

             *
      +             /
2      _      _      }
   +      +      *      *
 _  _   _  _   _  _   !  _
  2  2   1  1   ?  1   ?  1

How it works:

                ?            The input string (as a list of charcodes)
              __ *_1         (no-ops)
                    /        Group into sublists of length...
                     }       square root of...
                      !      length of...
                       ?     the input string again
                        *_1  (no-ops)
2_2+_2+__1+_1                Generate the number 10 in a needlessly complicated way
             *               Join the list of lists on 10 (newline)
                             Output the resulting list of numbers as a string
\$\endgroup\$
0
1
\$\begingroup\$

Convex, 7 bytes

_,mQ/N*

Try it online!

Fun fact:

_,mQ/\* also works on TIO due to how it works.

How have I forgotten to make a 1-char square root op?

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
",$a);
\$\endgroup\$
0
1
\$\begingroup\$

QBasic, 60 bytes

Nothing special here... just your BASIC program.

INPUT i$
t=SQR(len(i$))
FOR x=0TO t-1
?MID$(i$,x*t+1,t)
NEXT
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 28 27 bytes

-1 byte thanks to nwellnhof

{.comb(.comb**.5+|0)>>.say}

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ **.5 (or **½) is one byter shorter than .sqrt. \$\endgroup\$
    – nwellnhof
    Oct 14, 2018 at 11:35
  • \$\begingroup\$ @nwellnhof I always forget about that! Wouldn't it be nice if we could use the symbol instead? \$\endgroup\$
    – Jo King
    Oct 14, 2018 at 13:06
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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!
\$\endgroup\$
1
\$\begingroup\$

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!

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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 (/).

\$\endgroup\$
1
\$\begingroup\$

Zsh, 54 51 bytes

-3 by ^= instead of =0^().

((n=$#1,l^=n**0.5))
eval '<<<${1:'{0..$n..$l}':$l}'

Try it online! Try it online!

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.

\$\endgroup\$
1
\$\begingroup\$

Vyxal jr, 3 bytes

L√/

Try it Online!

  / # (Implicit input) divided into...
 √  # Square root of...
L   # Length of...
    # (implicit input)
  / # Pieces. 
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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).

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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 
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Ly, 31 bytes

irysp>l12/^s<[ol,s!['
o>s<1$]p]

Try it online!

Try a square version online, for fun

\$\endgroup\$
0
\$\begingroup\$

JavaScript (Node.js), 54 bytes

s=>[...s].map((c,i)=>++i%s.length**.5?c:c+`\n`).join``

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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;}
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Japt -R, 7 6 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
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.