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

65 Answers 65

0
\$\begingroup\$

Elm 0.19, 112 bytes

import List.Extra as L
s l=List.concat<|List.intersperse['\n']<|L.groupsOf(floor<|sqrt<|toFloat<|List.length l)l

Input and output as a list of characters. See it working here.

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

Tcl, 100 98 65 bytes

{s {regsub -all -- (.{[expr int([string le $s]**.5)]}) $s \\1\n}}

Try it online!

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

C#, 180 bytes

using System;public class P{public static void Main(string[]a){var d=(int)Math.Sqrt(a[0].Length);string f="";for(int i=0;i<d;i++){f+=a[0].Substring(i*d,d)+"\n";}Console.Write(f);}}

Try Online

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

MathGolf, 5 bytes

h√i/n

Try it online!

Unnecessarily long, the i shouldn't be needed in my opinion. For operators where float behavior is undefined, the float is normally cast to an integer and used in the operation. This seems to be forgotten for string division, which leads to the extra byte.

Explanation

h       length of array/string without popping
 √      pop a : push(sqrt(a))
  i     convert to integer
   /    split strings
    n   map array with newlines
\$\endgroup\$
0
\$\begingroup\$

Python 3, 54 bytes

lambda s:fill(s,int(len(s)**.5))
from textwrap import*

Try it online!

In Python 3 the textwrap module can be used to perform this task.

\$\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.