A square of text

29

5

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.

acrolith

Posted 2016-08-05T22:20:50.277

Reputation: 3 728

Can we assume that the input will never have new lines? – MayorMonty – 2016-08-06T02:13:47.507

@MayorMonty yep. – acrolith – 2016-08-06T02:20:21.007

2Can we output array of strings instead? – Leaky Nun – 2016-08-06T05:10:09.673

@LeakyNun no 15 chars – acrolith – 2016-08-06T16:58:13.317

2May we print with a trailing newline? – Giuseppe – 2017-10-04T15:53:54.877

Can it be a function or only full programs are allowed? – val says Reinstate Monica – 2019-07-09T14:01:54.967

Also, can we assume ASCII or UTF-8 support is required? – val says Reinstate Monica – 2019-07-09T14:03:46.200

Answers

10

05AB1E, 5 bytes

Dgtô«

Try it online!

D    duplicate a (implicit input)
g    length of a
t    square root of a
ô    push a split in pieces of b
«    join by newlines (implicit output)

acrolith

Posted 2016-08-05T22:20:50.277

Reputation: 3 728

1Great answer. But how does it work? Could you please [edit] to add an explanation? – grooveplex – 2016-08-06T13:22:57.937

@grooveplex done. – acrolith – 2016-08-06T15:51:21.120

Very impressive! – Gryphon – 2017-06-07T17:44:22.200

3It's weird to see old 05AB1E answers where » is newlines now. – Magic Octopus Urn – 2017-06-13T17:36:36.940

22

Vim, 59, 57, 48 bytes/keystrokes

$:let @q=float2nr(sqrt(col('.')))."|li<C-v><cr><C-v><esc>@q"<cr>@q

Since V is backwards compatible, you can Try it online!

I randomly received an upvote on this answer, so I looked over it again. My vim-golfing skills have greatly increased over the last 7 months, so I saw that this answer was very poorly golfed. This one is much better.

James

Posted 2016-08-05T22:20:50.277

Reputation: 54 537

15

Brainfuck, 116 112 bytes

>>>>,[[<]<<+>>>[>],]<[<]<+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>[<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

Try it online!

Safe in flavours of BF that does not mask the cells with 256, does not support null bytes.

Remove the initial right arrows if the flavour supports negative memory for 4 bytes saved.

Explanation

The program is divided into 3 stages:

Stage 1: >>>>,[[<]<<+>>>[>],]<[<]
Stage 2: <+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>
Stage 3: [<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]

Stage 1

In this stage, we put all the characters onto the tape, while keeping count of the number of characters.

This is the tape for the input abcdefghi after this tape:

000 009 000 000 095 096 097 098 099 100 101 102 103
             ^

The 009 is the count.

For each character, we move the the first zero on the left [<] and then add one to the count <<+>>>, and then move to the rightmost zero [>] to get ready for the next character.

Stage 2

This stage does the square root of the length stored in the second cell.

It keeps subtracting by 1, 3, 5, 7, ... until the number reaches zero, while keeping check of the number of iterations.

It works because square numbers can be expressed as 1 + 3 + 5 + ....

Stage 3

Denote the square root of the length found above as n.

This stage outputs n characters at a time, and then output a newline, until the tape is cleared.

Leaky Nun

Posted 2016-08-05T22:20:50.277

Reputation: 45 011

1+1 didnt read looks amazing though – Rohan Jhunjhunwala – 2016-08-06T22:50:45.820

11

Python 2, 55 bytes

s=input()
n=int(len(s)**.5)
while s:print s[:n];s=s[n:]

xnor

Posted 2016-08-05T22:20:50.277

Reputation: 115 687

8

MATL, 6 bytes

tnX^e!

Try it online!

Explanation

t     % Take input implicitly. Push another copy
n     % Get number of elements of the copy
X^    % Take square root
e     % Reshape the input into that number of rows, in column-major order
      % (which means: down, then across)
!     % Transpose so that text reads horizontally. Implicitly display

Luis Mendo

Posted 2016-08-05T22:20:50.277

Reputation: 87 464

1square "toor"? :P – acrolith – 2016-08-05T22:48:15.773

@daHugLenny :-D. Corrected – Luis Mendo – 2016-08-05T22:48:53.900

4@daHugLenny That's the inverse of the square root. ;-) – WBT – 2016-08-06T05:46:05.730

7

Jelly, 8 7 bytes

sLƽ$j⁷

Saved a byte thanks to @Dennis.

Try it online.

Explanation

sLƽ$j⁷  Input: string S
    $    Monadic chain
 L         Get the length of S
  ƽ       Take the integer square root of it, call it n
s        Split S into chunks of size n
     j⁷  Join using newline

miles

Posted 2016-08-05T22:20:50.277

Reputation: 15 654

2œs and s do the same thing here. – Dennis – 2016-08-05T22:48:11.037

Why does ½ not work instead of ƽ? – Luis Mendo – 2016-08-05T22:48:16.820

@LuisMendo Because it returns a float. I'll patch s and œs so they cast to int. – Dennis – 2016-08-05T22:49:08.340

@Dennis long-awaited patch still waiting... – Erik the Outgolfer – 2017-05-15T10:51:26.527

7

JavaScript (ES7), 49 bytes

s=>s.match(eval(`/.{${s.length**.5}}/g`)).join`
`

44 bytes in Firefox Nightly 43-46 only (** was introduced some time between Firefox Nightly 42 and 43 and g as a separate parameter was removed some time between Firefox Nightly 46 and 47):

s=>s.match(`.{${s.length**.5}}`,`g`).join`
`

Neil

Posted 2016-08-05T22:20:50.277

Reputation: 95 035

In the first version why do you need the + in s.length*+.5 – Downgoat – 2016-08-06T01:54:25.607

I've never seen the *+ syntax before. Could someone please explain it? – MayorMonty – 2016-08-06T02:25:05.390

He probably means **. – Conor O'Brien – 2016-08-06T05:53:57.470

@MayorMonty Yeah it was a typo sorry. – Neil – 2016-08-06T09:37:17.673

@Downgoat It was a typo sorry. – Neil – 2016-08-06T09:38:29.723

Interestingly enough, a*+b is parsed by JavaScript as a * (Number(b)), because of JavaScript's right to left operator parsing – MayorMonty – 2016-08-06T16:20:34.570

+1 for having your score be n². Mine is too :)

– Digital Trauma – 2016-08-06T22:50:06.797

@DigitalTrauma That doesn't seem to be that unusual... now what would be neat is an answer that was folded into a square of text! – Neil – 2016-08-06T22:56:55.947

Oh I'm loving the ** operator... this is a newly established ES7 feature? – WallyWest – 2016-08-09T00:36:08.450

@WallyWest https://tc39.github.io/ecma262/2016/#sec-exp-operator

– Neil – 2016-08-09T07:52:40.227

7

J, 9 bytes

$~,~@%:@#

This is a monadic hook over the input string:

$~ ,~@%:@#

The right tine is a series of compositions:

,~ @ %: @ #

The left is a shaping verb, switched such that it works in the hook format.

Here are some intermediate results:

   # 'hiya'
4
   %:@# 'hiya'
2
   ,~@%:@# 'hiya'
2 2

In words:

   size =: #
   sqrt =: %:
   dup =: ,~
   on =: @
   shape =: $~
   block =: shape dup on sqrt on size
   block 'Hello, World! :)'
Hell
o, W
orld
! :)

Conor O'Brien

Posted 2016-08-05T22:20:50.277

Reputation: 36 228

2I like the fact that $~,~@ resembles some sort of emoticon but @ seems weird for an ear but & fits better, or $~,~& – miles – 2016-08-06T06:13:18.930

1And I do suppose they are functionally equivalent. Well, mostly. One lets you hear better than the other ;) – Conor O'Brien – 2016-08-06T06:14:32.123

1

+1 for having your score be n². Mine is too :)

– Digital Trauma – 2016-08-06T22:49:42.433

@DigitalTrauma fun! +1 likewise! – Conor O'Brien – 2016-08-06T22:51:06.113

1$~2#%:@# is 8. The left part of a fork can be a constant. – FrownyFrog – 2017-10-05T11:22:03.813

5

Perl, 23 + 4 (-pF flags) = 27 bytes

-2 bytes thanks to @DomHastings
-1 bytes thanks to @DomHastings

$==sqrt@F;s/.{$=}/$&
/g

Try it online!

Expanations : computes the square root (lets call it S for the explanation) of the size of the input (it will be always be an integer) (@F is used in scalar context, thus returning its size), then add a newline after each bloc of S characters.

Dada

Posted 2016-08-05T22:20:50.277

Reputation: 8 279

Nice use of $@, ;) You can save a byte using y///c instead of length and I think you can use a literal new line as well. I was looking as trying to do something with setting $, and matching, but I think this is much shorter! – Dom Hastings – 2016-08-05T22:52:04.647

1@DomHastings Yea, I thought you'd like the $@! Thanks for the y///c, I tend to forget that it exists. – Dada – 2016-08-05T23:21:58.523

1@DomHastings managed to save 1 byte by using $= instead of $@, which allows to not use -l flag. – Dada – 2016-08-07T12:26:15.767

Good going! Good to use the magic variables for genuine reasons too! – Dom Hastings – 2016-08-07T14:00:00.040

Hey, hope you're doing alright! This got bumped to homepage and I noticed another optimisation for -1: 23 bytes code + 4 for -pF

– Dom Hastings – 2017-10-05T15:16:47.043

@DomHastings Hey! I'm fine, thanks, just a little bit busy, and not as motivated as I used to be! Thanks for the opti! :) – Dada – 2017-10-05T15:41:42.183

5

C, 64 bytes

Call f() with the string to square.

m;f(char*s){for(m=sqrt(strlen(s));*s;s+=m)printf("%.*s\n",m,s);}

Try it on ideone.

owacoder

Posted 2016-08-05T22:20:50.277

Reputation: 1 556

1Can you make it work with implicit int argument instead of char*? – anatolyg – 2016-08-07T07:31:58.963

I don't think so. It needs to be dereferenced, so a numeric type won't work, and it can't be an int* since that would scale wrong when adding. – owacoder – 2016-08-07T12:27:06.150

Suggest s+=write(puts(""),s,m)); instead of s+=m)printf("%.*s\n",m,s); – ceilingcat – 2018-10-11T06:16:33.043

4

Python, 94 75 71 65 63 bytes

import re;lambda r:"\n".join(re.findall("."*int(len(r)**.5),r))

Old version:

lambda r:"\n".join(map("".join,zip(*[iter(r)]*int(len(r)**.5))))

acrolith

Posted 2016-08-05T22:20:50.277

Reputation: 3 728

Note that you can use input() by default to receive input in quotes, unless you want to specifically remove that option.

– xnor – 2016-08-05T22:34:44.737

@xnor Oh wow, a few days ago I was wondering if I could use quotes on input... – acrolith – 2016-08-05T22:42:18.680

Wouldn't it be shorter to use a lambda? – Leaky Nun – 2016-08-06T04:58:13.410

@LeakyNun true... – acrolith – 2016-08-06T15:54:18.823

4

05AB1E, 8 6 bytes

Thanks to @quartata for letting me know about the square-root function

Dgtô¶ý

Try it online!

Explanation

D     Implicit input. Duplicate
g     Number of elements
t     Square root
ô     Split into chunks of that length
¶     Push newline character
ý     Join list by newlines. Implicit display

Luis Mendo

Posted 2016-08-05T22:20:50.277

Reputation: 87 464

Very nice! Also, « is short for joining on newlines :). – Adnan – 2016-08-05T23:13:53.620

1@Adnan Thanks! Now I have outgolfed myself :-D – Luis Mendo – 2016-08-05T23:21:33.147

I have rolled back to my 6-byte version because there was a previous answer with « – Luis Mendo – 2016-08-05T23:52:57.893

1Oh, that's too bad :( – Adnan – 2016-08-05T23:56:06.793

Does anyone else feel like those languages specifically created for code golf are kinda ruining the appeal of this whole thing? – René Roth – 2016-08-07T16:15:28.853

@RenéRoth Apparently yes. I don't necessarily agree with that position, though :-)

– Luis Mendo – 2016-08-07T16:57:40.687

4

zsh, 36 33 bytes

fold -`tr -d .<<<$[$#1**.5]`<<<$1

Try it online!

Takes input as a command line argument, outputs to STDOUT.

                   $#1             # get the length of the input string
                 $[   **.5]        # take it to the .5 power (sqrt)
              <<<                  # and pass the result to
       tr -d .                     # tr, to delete the trailing decimal point
                                   #    (sqrt(9) is 3. instead of 3)
     -`                    `       # give the result as a command line flag to
fold                               # the fold util, which wraps at nth column
                            <<<$1  # pass the input as input to fold

Doorknob

Posted 2016-08-05T22:20:50.277

Reputation: 68 138

+1 for having your score be n². Mine is too :)

– Digital Trauma – 2016-08-06T22:49:00.120

@DigitalTrauma Should you retract your upvote now? – pppery – 2019-12-26T16:50:09.373

3

Brain-Flak, 110 96 bytes

([]<>){({}{}(({}[()])))}{}{({}()<(({})<{({}()<<>({}<>)>)}{}((()()()()()){})>)>)}{}{}{({}<>)<>}<>

Try it online!

Second solution, 96 bytes

(([]<>)<{({}({})({}[()]))}{}>){({}(({})<{({}()<<>({}<>)>)}{}((()()()()()){})>))}{}{}{({}<>)<>}<>

Try it online!

Explanation

Here I explain the first solution, both are the same length but I like the first one because it is cooler and employs some nice tricks.

The most important part of the code is a modified square root function I wrote some time ago. The original version was

{({}[({})({}())])}{}

And this works, but we actually want two copies of the negative square root. Why? We need two copies because we are looping through the string at two levels, one to make the lines and one to count the number of lines. We want it to be negative because looping with negatives is cheaper.

To make this negative we move around the [...] so it looks like this

{({}({})({}[()]))}{}

To make two copies we change when pops occur

{({}{}(({}[()])))}{}

Now that we have that bit we can put it together with a stack height to get the first chunk of code we need.

([]<>){({}{}(({}[()])))}{}

We move to the offstack because our square root function needs two free zeros for computation, and because it makes stuff a little bit cheaper int he future in terms of stack switching.

Now we construct the main loop

{({}()<(({})<{({}()<<>({}<>)>)}{}((()()()()()){})>)>)}{}{}

This is pretty straight forward, we loop n times each time moving n items and capping it with a new line (ASCII 10).

Once the loop is done we need to reverse the order of our output so we just tack on a standard reverse construct.

{({}<>)<>}<>

Post Rock Garf Hunter

Posted 2016-08-05T22:20:50.277

Reputation: 55 382

Also 96 – H.PWiz – 2017-10-04T17:23:18.817

3

CJam, 8 bytes

l_,mQ/N*

Try it online!

Explanation

l     e# Read line from input
_,    e# Duplicate. Get length 
mQ    e# Integer square root
/     e# Split into pieces of that size
N*    e# Join by newline. Implicitly display

Luis Mendo

Posted 2016-08-05T22:20:50.277

Reputation: 87 464

3

Pyth, 8 bytes

jcs@lQ2Q

Try it online

How it works

    lQ     length of input
   @  2    square root
  s        floor
 c     Q   chop input into that many equal pieces
j          join on newline

Anders Kaseorg

Posted 2016-08-05T22:20:50.277

Reputation: 29 242

3

Cheddar, 27 bytes (non-competing)

s->s.chunk(s.len**.5).vfuse

I added the .chunk function a while ago but I removed it in the transition to the new stdlib format and forgot to re-add it. Cheddar has a dedicated sqrt operator but **.5 is shorter

Try it online!

Explanation

s ->              // Function with argument s
    s.chunk(      // Chunk it into pieces of size...
      s.len ** .5 // Square root of length.
    ).vfuse       // Vertical-fuse. Join on newlines

Downgoat

Posted 2016-08-05T22:20:50.277

Reputation: 27 116

3

Dyalog APL, 10 bytes

⊢⍴⍨2⍴.5*⍨≢

Explanation:

         ≢   length of the argument   
     .5*⍨    square root 
   2⍴        reshape that to a length-2 vector
⊢⍴⍨          reshape the input by that vector

Tests:

      (⊢⍴⍨2⍴.5*⍨≢)'Hi, world'
Hi,
 wo
rld
      (⊢⍴⍨2⍴.5*⍨≢)'Hi, world! Hello'
Hi, 
worl
d! H
ello
      (⊢⍴⍨2⍴.5*⍨≢)'Lorem ipsum dolor sit amt'
Lorem
 ipsu
m dol
or si
t amt
      (⊢⍴⍨2⍴.5*⍨≢) 'H'
H

marinus

Posted 2016-08-05T22:20:50.277

Reputation: 30 224

3

Bash + GNU utilities, 25

fold -`dc -e${#1}vp`<<<$1

Not so different to @Doorknob's answer, but dc is a shorter way to get the square root.

Digital Trauma

Posted 2016-08-05T22:20:50.277

Reputation: 64 644

3

, 11 chars / 14 bytes

ѨĊ(ï,√ ïꝈ⸩Ė⬮

Try it here (ES6 browsers only).

Generated using this code (run in the interpreter's browser console):

c.value=`Ѩ${alias(_,'chunk')}(ï,√ ïꝈ⸩${alias(Array.prototype,'mjoin')}⬮`

Mama Fun Roll

Posted 2016-08-05T22:20:50.277

Reputation: 7 234

3

Brainfuck, 83 bytes

,[>+[>+<-],]
>
[
  >>[<+<-->>-]
  +<[>+<-]
  <-
]
<<
[
  [<]
  >.,
  >[>]
  >>+>-[<]
  <[[>+<-]++++++++++.,<<]
  <
]

Try it online!

This uses the same idea as Leaky Nun's answer. He asked for help golfing it in chat, then suggested that I add this as a new answer. (Actually what I wrote in chat was an 84-byte solution very similar to this.)

For the sake of comparison, an extra > is needed at the beginning for brainfuck implementations that don't allow negative memory addresses.

As expected, this finds the length of the input, then takes the square root, then prints the lines accordingly. It takes advantage of perfect squares being partial sums of 1 + 3 + 5 ....

Mitch Schwartz

Posted 2016-08-05T22:20:50.277

Reputation: 4 899

2

R, 59 54 bytes

function(s)write(el(strsplit(s,'')),1,nchar(s)^.5,,'')

Try it online!

Prints with a trailing newline. Surprisingly short, considering how badly R handles strings.

Giuseppe

Posted 2016-08-05T22:20:50.277

Reputation: 21 077

2

PHP, 51 bytes

<?=join("
",str_split($x=$argv[1],strlen($x)**.5));

Alex Howansky

Posted 2016-08-05T22:20:50.277

Reputation: 1 183

2

Perl 6, 38 bytes

$_=get;.put for .comb: .chars.sqrt.Int

Explanation:

$_ = get;          # get a single line of input


$_.put             # print with trailing newline

for                # every one of the following:

$_.comb:           # the input split into

$_.chars.sqrt.Int  # chunks of the appropriate size

Brad Gilbert b2gills

Posted 2016-08-05T22:20:50.277

Reputation: 12 713

2

Ruby -p, 40 33 30 bytes

-7 bytes from @Jordan.

gsub(/#{?.*~/$/**0.5}/){$&+$/}

Try it online!

Value Ink

Posted 2016-08-05T22:20:50.277

Reputation: 10 608

2

Cheddar, 57 bytes

n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5)

Since variables are broken, I would have to pass in variables through lambda application.

Also, it turns out that even if variables worked, it would still be shorter to use lambda application.

Usage

cheddar> (n->(m->(|>m).map(i->n.slice(i*m,i*m+m)).vfuse)(n.len**.5))("abcd")
"ab
cd"

Leaky Nun

Posted 2016-08-05T22:20:50.277

Reputation: 45 011

2

Pyke, 5 bytes

l,fnJ

Try it here!

Blue

Posted 2016-08-05T22:20:50.277

Reputation: 26 661

2

PowerShell, 56 58 61 bytes

param($i)$i-replace".{$([Math]::Sqrt($i.Length))}",'$&
'

Joey

Posted 2016-08-05T22:20:50.277

Reputation: 12 260

Taking it as a param saves two bytes – Veskah – 2019-07-08T15:36:11.710

2

Java 1.7, 110 bytes

void f(String s){for(int i=-1,k=(int)Math.sqrt(s.length());++i<k;)System.out.println(s.substring(i*k,i*k+k));}

Try it! (Ideone)

I tried another approach with a function returning the result as a string, but just having to declare the string and the return statement is already more expensive (byte-count-wise) than the print statement.

Gotta love Java's verbosity... :)

MH.

Posted 2016-08-05T22:20:50.277

Reputation: 261

Nice answer +1. You can golf it by 1 byte by using i=0, i<k and s.substring(i*k,i++*k+k) instead of i=-1, ++i<k, s.substring(i*k,i*k+k). Also, usually we use just Java 7 instead of Java 1.7, but it's good that you've added it, a lot of people forget to do so. – Kevin Cruijssen – 2016-09-07T08:58:05.430

1

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

streetster

Posted 2016-08-05T22:20:50.277

Reputation: 3 635

1

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

dzaima

Posted 2016-08-05T22:20:50.277

Reputation: 19 048

1

Perl 6, 28 27 bytes

-1 byte thanks to nwellnhof

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

Try it online!

Jo King

Posted 2016-08-05T22:20:50.277

Reputation: 38 234

1**.5 (or **½) is one byter shorter than .sqrt. – nwellnhof – 2018-10-14T11:35:48.253

@nwellnhof I always forget about that! Wouldn't it be nice if we could use the symbol instead? – Jo King – 2018-10-14T13:06:30.757

1

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)

Esolanging Fruit

Posted 2016-08-05T22:20:50.277

Reputation: 13 542

1

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.

mprogrammer

Posted 2016-08-05T22:20:50.277

Reputation: 461

1

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!

Alex Papageorgiou

Posted 2016-08-05T22:20:50.277

Reputation: 41

1

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!

Dat

Posted 2016-08-05T22:20:50.277

Reputation: 879

1

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

Khuldraeseth na'Barya

Posted 2016-08-05T22:20:50.277

Reputation: 2 608

1

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.

GammaFunction

Posted 2016-08-05T22:20:50.277

Reputation: 2 838

1

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

scrawl

Posted 2016-08-05T22:20:50.277

Reputation: 1 079

1

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?

GamrCorps

Posted 2016-08-05T22:20:50.277

Reputation: 7 058

1

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.

pajonk

Posted 2016-08-05T22:20:50.277

Reputation: 2 480

1

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

Crypto

Posted 2016-08-05T22:20:50.277

Reputation: 862

1

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

GuitarPicker

Posted 2016-08-05T22:20:50.277

Reputation: 1 101

0

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

Shaggy

Posted 2016-08-05T22:20:50.277

Reputation: 24 623

0

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

streetster

Posted 2016-08-05T22:20:50.277

Reputation: 3 635

0

Ly, 31 bytes

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

Try it online!

Try a square version online, for fun

LyricLy

Posted 2016-08-05T22:20:50.277

Reputation: 3 313

0

JavaScript (Node.js), 54 bytes

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

Try it online!

ggorlen

Posted 2016-08-05T22:20:50.277

Reputation: 121

0

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.

Josh B.

Posted 2016-08-05T22:20:50.277

Reputation: 105

0

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;}

AkhilKumar

Posted 2016-08-05T22:20:50.277

Reputation: 31

0

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

Oliver

Posted 2016-08-05T22:20:50.277

Reputation: 7 160

0

Tcl, 100 98 65 bytes

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

Try it online!

SmileAndNod

Posted 2016-08-05T22:20:50.277

Reputation: 119

0

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.

mprogrammer

Posted 2016-08-05T22:20:50.277

Reputation: 461

0

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.

val says Reinstate Monica

Posted 2016-08-05T22:20:50.277

Reputation: 409

0

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

Draco18s no longer trusts SE

Posted 2016-08-05T22:20:50.277

Reputation: 3 053

0

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.

O.O.Balance

Posted 2016-08-05T22:20:50.277

Reputation: 1 499

0

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

canttalkjustcode

Posted 2016-08-05T22:20:50.277

Reputation: 131

0

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

maxb

Posted 2016-08-05T22:20:50.277

Reputation: 5 754

0

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.

Joel

Posted 2016-08-05T22:20:50.277

Reputation: 1 691

0

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

downrep_nation

Posted 2016-08-05T22:20:50.277

Reputation: 1 152

0

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

anatolyg

Posted 2016-08-05T22:20:50.277

Reputation: 10 719

0

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 

m654

Posted 2016-08-05T22:20:50.277

Reputation: 765

0

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.

ATaco

Posted 2016-08-05T22:20:50.277

Reputation: 7 898

0

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

rnso

Posted 2016-08-05T22:20:50.277

Reputation: 1 635

0

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

acrolith

Posted 2016-08-05T22:20:50.277

Reputation: 3 728

0

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.

steenbergh

Posted 2016-08-05T22:20:50.277

Reputation: 7 772