텍스트의 제곱


29

도전

문자열이 주어지면 사각형 모양으로 텍스트를 출력하십시오.

텍스트가 항상 square에 맞고 빈 문자열이 아니라고 가정 할 수 있습니다 .

또한 줄 바꿈이 없을 것이라고 가정 할 수도 있습니다.

Input:
Hi, world

Output:
Hi,
 wo
rld

테스트 사례

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

규칙

  • 이것은 이므로 바이트 단위의 최단 답변이 승리합니다! Tiebreaker가 가장 큰 답입니다.
  • 표준 허점은 금지되어 있습니다.

입력에 새로운 줄이 없다고 가정 할 수 있습니까?
MayorMonty

@MayorMonty 네.
아크로리스

2
대신 문자열 배열을 출력 할 수 있습니까?
Leaky Nun

@LeakyNun no 15 chars
acrolith

2
후행 줄 바꿈으로 인쇄 할 수 있습니까?
Giuseppe

답변:


21

Vim, 59, 57 , 48 바이트 / 키 스트로크

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

V는 이전 버전과 호환 되므로 온라인으로 사용해 볼 수 있습니다!

나는이 답변에 대한 찬성 투표를 무작위로 받았으므로 다시 살펴 보았습니다. 지난 7 개월 동안 저의 vim-golfing 기술이 크게 향상 되었기 때문에이 답변의 골프 수준이 매우 낮았습니다. 이것은 훨씬 낫습니다.


15

브레인 퍽 , 116 112 바이트

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

온라인으로 사용해보십시오!

로 셀을 마스킹하지 않는 BF의 풍미에서 안전하며 256null 바이트를 지원하지 않습니다.

플레이버가 4 바이트 동안 네거티브 메모리를 지원하는 경우 초기 오른쪽 화살표를 제거하십시오.

설명

이 프로그램은 3 단계로 나뉩니다.

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

스테이지 1

이 단계에서는 모든 문자를 테이프에 넣고 문자 수를 계산합니다.

이 테이프 다음에 입력 abcdefghi할 테이프입니다.

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

009계수이다.

각 문자에 대해 왼쪽의 첫 번째 0 을 이동 한 다음 [<]count에 1을 더한 <<+>>>다음 가장 오른쪽의 0 [>]으로 이동 하여 다음 문자를 준비합니다.

2 단계

이 단계는 두 번째 셀에 저장된 길이의 제곱근을 수행합니다.

1, 3, 5, 7, ...반복 횟수를 확인하면서 숫자가 0에 도달 할 때까지 빼기를 계속합니다.

사각형 숫자는로 표현 될 수 있기 때문에 작동합니다 1 + 3 + 5 + ....

3 단계

위에서 찾은 길이의 제곱근을 나타냅니다 n.

이 단계 n에서는 한 번에 문자를 출력 한 다음 테이프가 지워질 때까지 줄 바꿈을 출력합니다.


1
+1은 읽히지 않았지만 놀랍습니다
Rohan Jhunjhunwala

11

파이썬 2, 55 바이트

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

10

05AB1E , 5 바이트

Dgtô«

온라인으로 사용해보십시오!

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)

1
좋은 대답입니다. 그러나 어떻게 작동합니까? 당신은 기쁘게 할 수 편집 에 대한 설명을 추가?
grooveplex

@grooveplex가 완료되었습니다.
acrolith

매우 인상적!
그리폰-복원 모니카

3
오래된 05AB1E »가 지금 줄 바꿈이 어디에 있는지 대답하는 것이 이상합니다 .
Magic Octopus Urn

8

MATL , 6 바이트

tnX^e!

온라인으로 사용해보십시오!

설명

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

1
광장 "투"? : P
acrolith

@daHugLenny :-D. 수정
루이스 멘도

4
@daHugLenny 제곱근의 역수입니다. ;-)
WBT

7

젤리, 8 7 바이트

sLƽ$j⁷

@ Dennis 덕분에 바이트를 절약했습니다 .

온라인으로 사용해보십시오.

설명

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

2
œs그리고 s여기에 같은 일을.
Dennis

½대신 작동하지 ƽ않습니까?
Luis Mendo

@LuisMendo float를 반환하기 때문입니다. 패치 s하고 œsint로 캐스팅합니다.
Dennis

@Dennis 오랫동안 기다려온 패치가 아직 기다리고 있습니다 ...
Outgolfer Erik

7

자바 스크립트 (ES7), 49 바이트

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

Firefox Nightly 43-46에서만 44 바이트 ( **Firefox Nightly 42와 43 사이에 일정 시간 도입 g되었으며 Firefox Nightly 46과 47 사이에 별도의 매개 변수가 제거됨) :

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

첫 번째 버전에서 당신은 왜 필요합니까 +에서s.length*+.5
Downgoat

나는 *+전에 구문을 본 적이 없다 . 누군가 설명해 주시겠습니까?
MayorMonty

그는 아마도 의미 **합니다.
Conor O'Brien

@MayorMonty 그래 오타 미안했다.
Neil

@ Downgoat 죄송합니다.
Neil

7

J, 9 바이트

$~,~@%:@#

이것은 입력 문자열에 대한 모나 딕 후크입니다.

$~ ,~@%:@#

올바른 타인은 일련의 구성입니다.

,~ @ %: @ #

왼쪽은 성형 동사이며 후크 형식으로 작동하도록 전환되었습니다.

중간 결과는 다음과 같습니다.

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

한마디로 :

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

2
I like the fact that $~,~@ resembles some sort of emoticon but @ seems weird for an ear but & fits better, or $~,~&
miles

1
And I do suppose they are functionally equivalent. Well, mostly. One lets you hear better than the other ;)
Conor O'Brien

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

@DigitalTrauma fun! +1 likewise!
Conor O'Brien

1
$~2#%:@# is 8. The left part of a fork can be a constant.
FrownyFrog

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.


1
Can you make it work with implicit int argument instead of char*?
anatolyg

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

Suggest s+=write(puts(""),s,m)); instead of s+=m)printf("%.*s\n",m,s);
ceilingcat

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.


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

1
@DomHastings Yea, I thought you'd like the $@! Thanks for the y///c, I tend to forget that it exists.
Dada

1
@DomHastings managed to save 1 byte by using $= instead of $@, which allows to not use -l flag.
Dada

Good going! Good to use the magic variables for genuine reasons too!
Dom Hastings

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

4

zsh, 36 bytes

fold -`sed s/.$//<<<$[$#1**.5]`<<<$1

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
       sed s/.$//                     sed, which removes the last character
                                      this is because 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

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

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

Very nice! Also, « is short for joining on newlines :).
Adnan

1
@Adnan Thanks! Now I have outgolfed myself :-D
Luis Mendo

I have rolled back to my 6-byte version because there was a previous answer with «
Luis Mendo

1
Oh, that's too bad :(
Adnan

Does anyone else feel like those languages specifically created for code golf are kinda ruining the appeal of this whole thing?
René Roth

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

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

@xnor Oh wow, a few days ago I was wondering if I could use quotes on input...
acrolith

Wouldn't it be shorter to use a lambda?
Leaky Nun

@LeakyNun true...
acrolith

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

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

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

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


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')}⬮`

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


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.

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



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

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"


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


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

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.




당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.