텍스트를 세로로 축소


85

이 같은 텍스트가 있다고 가정하십시오 (각 단어는 공백없이 한 줄에 있습니다)

Programming
Puzzles
&
Code
Golf

말이되지 않습니다! 그것은 물리 법칙을 완전히 무시합니다.

당신의 도전은이 불가능한 상황을 해결하고 다음과 같이 텍스트를 접는 것입니다.

P
Prog
&uzz
Coderam
Golflesming

문자 아래에 빈 공간이 없지만 문자는 수직 순서를 유지합니다.

목표는 요구 사항을 만족하지만 가능한 적은 바이트의 소스 코드를 사용하는 것입니다.


12
또한 한 줄에 한 단어입니까, 공백이 있습니까? 공간이 있으면 공간이 축소되어야합니까, 아니면 공간이 가중 될 수 있습니까?
— Glen O

53
"P Prog & uzz Coderam Golflesming", 사이트 제목에 대한 새로운 후보가있는 것
— 같습니다

1
누군가 Marbelous ( github.com/marbelous-lang/marbelous.py ) 를 사용할 예정 입니까?
— Charlie

1
나는 물리 엔진을 사용하고 0 바이트를 개최하기로 결정
— l4m2

2
출력에 후행 공백이있을 수 있습니까?
— Outgolfer Erik

답변:


57

Pyth, 10 바이트

jb_.T.T_.z

Pyth Compiler / Executor 에서 온라인으로 사용해보십시오 .

생각

4 가지 간단한 변환을 적용하여 원하는 결과를 얻을 수 있습니다.

  1. 줄의 순서를 반대로 바꿉니다.

    Golf
    Code
    &
    Puzzles
    Programming
    
  2. 행과 열을 바꿉니다.

    GC&PP
    oour
    ldzo
    fezg
    lr
    ea
    sm
    m
    i
    n
    g
    

    이 상단은 원래 열을 축소하고 정당화합니다.

  3. 행과 열을 바꿉니다.

    Golflesming
    Coderam
    &uzz
    Prog
    P
    
  4. 줄의 순서를 반대로 바꿉니다.

    P
    Prog
    &uzz
    Coderam
    Golflesming
    

암호

        .z  Read the input as a list of strings, delimited by linefeeds.
       _    Reverse the list.
   .T.T     Transpose the list twice.
  _         Reverse the list.
jb          Join its strings; separate with linefeeds.

1
Grr, 정확히 이것을 게시하려고했습니다 :). 대신 공감대를 가지십시오.
— Maltysen

나도 비슷한 것을 게시 할 계획이 있었는데 ... 공감도
— WallyWest

주문을 취소하기 전에 행과 열을 바꾸면 어떻게됩니까?
— 존 오돔

1
@JohnOdom 단순히 두 번 조바꿈하면 문자가 맨 아래로 이동하지 않고 맨 위로 이동합니다. 조옮김으로 시작할 수 있습니다. 그러면 각 행을 바꿔야합니다. 1 바이트 더 길어집니다.
— Dennis

Holy FoxPro, 이것은 영리했습니다.
— workoverflow

38

하스켈, 62 바이트

import Data.List
p=reverse;o=transpose
f=unlines.p.o.o.p.lines

나는 매우 성숙하다.


20
+1 Haskell을 거의 보지 못하고 줄 바꿈을하기 때문에
— Carcigenicate

17

파이썬 2, 104 바이트

l=[]
for x in input().split('\n'):n=len(x);l=[a[:n]+b[n:]for a,b in zip(l+[x],['']+l)]
print'\n'.join(l)

반복적 인 원 패스 알고리즘. 각 줄을 순서대로 l살펴보고 출력 할 줄 목록 을 업데이트합니다 . 새로운 단어는 바닥에서 효과적으로 밀려 나고 그 위에있는 모든 글자를 한 칸 띄웁니다. 예를 들어 테스트 사례에서

Programming
Puzzles
&
Code
Golf

우리가까지 완료 한 후에 Code, 우리는이

P
Prog
&uzzram
Codelesming

그런 다음 Golf결과 를 추가

P
Prog
&uzz
Coderam
Golflesming

우리는 두 조각의 조합으로 볼 수 있습니다

P     |
Prog  |
&uzz  |
Code  | ram
Golf  | lesming

첫 번째 조각이에 의해 이동되었습니다 golf. 우리 zip는 출력 목록 중 하나를 끝 (왼쪽)에 요소와 출력 목록 우선 순위를 빈 줄 (오른쪽)로하여 이동을 수행하여 새 요소의 길이에서 각 부분을 잘라냅니다.

새로운 문자가 맨 위에서 떨어지게하는 대신 거꾸로 반복하는 것이 더 자연스러워 보일 수 있지만 그 시도는 더 길어졌습니다.

비교를 위해 (109 바이트)에 사용되는 zip/ filter접근 방식은 다음과 같습니다.map(None,*x)iziplongest

f=lambda z:[''.join(filter(None,x))for x in map(None,*z)]
lambda x:'\n'.join(f(f(x.split('\n')[::-1]))[::-1])

12

CJam, 11 바이트

qN/W%zzW%N*

CJam 통역사 에서 온라인으로 사용해보십시오 .

작동 원리

내 Pyth 답변 과 같은 아이디어 .

q           e# Read from STDIN.
 N/         e# Split at linefeeds.
   W%       e# Reverse the resulting array.
     zz     e# Transpose it twice.
       W%   e# Reverse the resulting array.
         N* e# Join its strings; separate with linefeeds.

7

자바 스크립트 (ES6), 146

(템플릿 문자열 안에있는 2 개의 줄 바꿈은 중요하고 계산됩니다)

@Dennis의 아이디어는 JavaScript로 구현되었습니다. 긴 S 함수는 행 단위로 조옮김을 수행하고 char 단위로 문자를 변환하여 결과를 t배열 에 남겨 둡니다 .

a=>(S=z=>{for(t=[];z.join``;t.push(w))for(w='',n=z.length;n--;z[n]=z[n].slice(1))w+=z[n][0]||''},S(a.split`
`),S(t.reverse()),t.reverse().join`
`)

스 니펫 내에서 덜 골프를칩니다 (Firefox에서 시도).

F=a=>(
  S=z=>{
    for(t=[];z.join``;t.push(w))
      for(w='',n=z.length;n--;z[n]=z[n].slice(1))
        w+=z[n][0]||''
  },
  S(a.split`\n`),
  S(t.reverse()),
  t.reverse().join`\n`
)
#I,#O { margin:0; width: 200px; height:100px; border: 1px solid #ccc }
<table><tr><td>
Input<br><textarea id=I>Programming
Puzzles
&
Code
Golf
</textarea></td><td>
Output<pre id=O></pre>
</td></tr></table>  
<button onclick='O.innerHTML=F(I.value)'>go</button>


로 교체하여 몇 바이트를 줄 S(t.reverse()),t.reverse().join입니다 S(R=t.reverse()),R.join.
— Ismael Miguel

@IsmaelMiguel 아니오, S는 t를 변경하므로 S 이후의 t는 S 이전의 t와 같지 않습니다
— edc65

5

R, 223 바이트

function(x){a=apply(do.call(rbind,lapply(p<-strsplit(strsplit(x,"\n")[[1]],""),function(x)c(x,rep(" ",max(lengths(p))-length(x))))),2,function(x)c(x[x==" "],x[x!=" "]));for(i in 1:nrow(a))cat(a[i,][a[i,]!=" "],"\n",sep="")}

이것은 터무니없이 길고 순진한 방법입니다.

언 골프 드 :

f <- function(x) {
    # Start by spliting the input into a vector on newlines
    s <- strsplit(x, "\n")[[1]]

    # Create a list consisting of each element of the vector
    # split into a vector of single characters
    p <- strsplit(s, "")

    # Pad each vector in p to the same length with spaces
    p <- lapply(p, function(x) c(x, rep(" ", max(lengths(p)) - length(x))))

    # Now that the list has nice dimensions, turn it into a matrix
    d <- do.call(rbind, p)

    # Move the spaces to the top in each column of d
    a <- apply(d, 2, function(x) c(x[x == " "], x[x != " "]))

    # Print each row, omitting trailing whitespace
    for (i in 1:nrow(a)) {
        cat(a[i, ][a[i, ] != " "], "\n", sep = "")
    }
}

당신은 할 수 있습니다 온라인으로보십시오 .


5

Matlab / 옥타브, 99 바이트

function f(s)
c=char(strsplit(s,[10 '']));[~,i]=sort(c>32);[m,n]=size(c);c(i+repmat((0:n-1)*m,m,1))

예 :

변수에 입력 문자열을 정의하십시오 (예 :) s. 10줄 바꿈 문자입니다.

>> s = ['Programming' 10 'Puzzles' 10 '&' 10 'Code' 10 'Golf'];

f입력 된 함수 호출 s:

>> f(s)
ans =
P          
Prog       
&uzz       
Coderam    
Golflesming

또는 온라인으로 사용해보십시오 ( 온라인 옥타브 통역사와의 도움을 위해 @beaker 에게 감사드립니다 )


4

자바 스크립트 ES6, 119 바이트

F=s=>(C=o=>--a.length?C(a.reduce((p,c,i)=>c+p.slice((a[i-1]=p.slice(0,c.length)).length)))+`
`+o:o)(a=(s+`
`).split`
`)

여기에 ungolfed 및 ES5에서 작동 방식을 설명하는 주석이 있습니다.

function F(s) {
  var arr = (s+'\n').split('\n'); // Create an array of words and append an empty member
  return (function C(output) {
    return --arr.length ? // Remove the last item from the array
      C(arr.reduce(function(p,c,i) { // If the array still has length reduce it to a string and recurse
        var intersection = (arr[i-1] = p.slice(0, c.length)) // Overwrite the previous word with the part that intersects the current word
        return c + p.slice(intersection.length) // Add the part of the previous word that doesn't intersect to the current value
      })) + '\n' + output : output // Add the last level of recursions output on to the end of this
  })(arr);
}

input.addEventListener('input', updateOutput, false);

function updateOutput() {
  var oldLength = input.value.length;
  var start = this.selectionStart;
  var end = this.selectionEnd;
  input.value = input.value.split(/ +/).join('\n');
  var newLength = input.value.length;
  input.setSelectionRange(start, end + (newLength - oldLength));
  output.value = F(input.value).trim();
}

updateOutput();
textarea {
  width: 50%;
  box-sizing: border-box;
  resize: none;
  float: left;
  height: 10em;
}

label {
  width: 50%;
  float: left;
}
<p>Type in the input box below, spaces are automatically converted to newlines and the output updates as you type</p>
<label for="input">Input</label>
<label for="output">Output</label>
<textarea id="input">
Type inside me :)
</textarea>
<textarea id="output" disabled>
</textarea>



3

R, 190 (178) 175 바이트

아마 아직도 골프를위한 여지가있을 것입니다. 아마도 몇 가지 불필요한 작업이 있습니다.

l=lapply;s=substring;C=rbind;d=do.call;cat(C(d(C,l(apply(d(C,l(a<-scan(,''),s,1:(w=max(nchar(a))),1:w))[(h=length(a)):1,],2,paste0,collapse=''),s,1:h,1:h))[,h:1],'\n'),sep='')

언 골프 및 설명

a<-scan(,'')    # get STDIN
h<-length(a)    # number of lines
w=max(nchar(a)) # length of longest line
M<-lapply(a,substring,1:w,1:w)   # create a list of split strings with empty chars
M<-do.call(rbind,M)[h:1,]        # turn it into a matrix with line order reversed
M<-apply(M,1,paste0,collapse='') # paste together the columns
M<-lapply(M,substring,1:h,1:h)   # split them back up
M<-do.call(rbind,M)[,h:1]        # reform a matrix
M<-rbind(M,'\n')                 # add some carriage returns
cat(M,sep='')   # output with seperators

시운전. 스캔이 작동하는 방식으로 인해 전체 문장을 공백으로 입력하고 지정된대로 출력을 줄 수 있습니다.

> l=lapply;s=substring;C=rbind;d=do.call;cat(C(d(C,l(apply(d(C,l(a<-scan(,''),s,1:(w=max(nchar(a))),1:w))[(h=length(a)):1,],2,paste0,collapse=''),s,1:h,1:h))[,h:1],'\n'),sep='')
1: Programming
2: Puzzles
3: &
4:     Code
5: Golf
6: 
Read 5 items
P
Prog
&uzz
Coderam
Golflesming
> l=lapply;s=substring;C=rbind;d=do.call;cat(C(d(C,l(apply(d(C,l(a<-scan(,''),s,1:(w=max(nchar(a))),1:w))[(h=length(a)):1,],2,paste0,collapse=''),s,1:h,1:h))[,h:1],'\n'),sep='')
1: Programming Puzzles & Code Golf beta
7: 
Read 6 items
P
Prog
&uzz
Code
Golfram
betalesming
>   

3

STATA, 323 바이트

ab라는 파일에 입력합니다. 이제 최대 24 자까지만 사용할 수 있습니다. 나중에 더 잘 작동하도록 업데이트합니다. 또한 온라인 컴파일러에서는 작동하지 않습니다. 무료 컴파일러가 필요합니다.

gl l=24/
forv x=1/$l{
gl a="$a str a`x' `x'"
}
infix $a using a.b
gl b=_N
forv k=1/$l{
gen b`k'=0
qui forv i=$b(-1)1{
forv j=`i'/$b{
replace b`k'=1 if _n==`j'&a`k'==""
replace a`k'=a`k'[_n-1] if _n==`j'&a`k'==""
replace a`k'="" if _n==`j'-1&b`k'[_n+1]==1
replace b`k'=0
}
}
}
forv i=1/$b{
forv k=1/$l{
di a`k'[`i'] _c
}
di
}

편집 : 조용히 (출력을 억제하기 위해) 루프의 각 명령문에서 루프 자체로 이동하여 8 바이트를 절약합니다.


무료 컴파일러가 아닌 제출이 왜 유효하지 않은 제출입니까?
— Dennis

@Dennis 나는 메타에서 프로그래밍 언어를 일부 무료 환경에서 실행할 수 있어야한다고 결정했습니다. 또한 입력 길이 제한으로 인해 무효화 될 수 있습니다.
— bmarks

1
문자 제한은 문제가 될 수 있지만 무료 구현이 필요한 메타 합의는 알 수 없습니다. (Hello World 퀴즈에서이 아이디어를 얻은 경우 해당 질문에 명시 적으로 무료 언어를 요청했습니다.)
— Dennis

@Dennis 나는 이것이 합의라고 생각했다 : meta.codegolf.stackexchange.com/questions/988/…
— bmarks

대답은 실제로 합의가 필요하지 않고 실제로는 발생하지 않는 테스트 할 수없는 게시물을 거부한다고 제안합니다. 실제로 Mathematica 및 TI-BASIC 답변은 일반적으로 매우 인기가 있습니다.
— Dennis

2

R, 171 바이트

S=scan(,"");while(any((D<-diff(N<-sapply(S,nchar)))<0)){n=max(which(D<0));S[n+1]=paste0(S[n+1],substr(S[n],N[n]+D[n]+1,N[n]));S[n]=substr(S[n],1,N[n]+D[n])};cat(S,sep="\n")

줄 바꿈과 들여 쓰기 :

S=scan(,"") #Takes input from stdin
while(any((D<-diff(N<-sapply(S,nchar)))<0)){
    n=max(which(D<0))
    S[n+1]=paste0(S[n+1],substr(S[n],N[n]+D[n]+1,N[n]))
    S[n]=substr(S[n],1,N[n]+D[n])
}
cat(S,sep="\n")

용법:

> S=scan(,"");while(any((D<-diff(N<-sapply(S,nchar)))<0)){n=max(which(D<0));S[n+1]=paste0(S[n+1],substr(S[n],N[n]+D[n]+1,N[n]));S[n]=substr(S[n],1,N[n]+D[n])};cat(S,sep="\n")
1: Programming
2: Puzzles
3: &
4: Code
5: Golf
6: 
Read 5 items
P
Prog
&uzz
Coderam
Golflesming


2

Turtlèd , 72 바이트, 비경쟁

분명히 바이트를 절약하기 위해 접근 방식을 변경할 수 있지만 나중에는 가능합니다.

: p 비 골프 esolang이 일반 언어를 이겼습니다 : p

Turtlèd의 이상한 점은 원래 아스키 아트 랭에 대한 토론 후에 만들어진 것이지만 실제로는 이러한 종류의 도전에서 최고인 것 같습니다.

Turtlèd는 줄 바꿈 입력을 할 수 없지만 여러 입력에 대해서는 한 번만 입력하면됩니다. 마지막 단어를 포함하여 공백으로 각 단어를 종료합니다.

!l[*,+r_][ l]ur[*,[ -.]+.[ r{ d}u+.]-.[ -.]{ l}[ l]r[ u]_]' d[ d]u[ ' r]

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

설명:

!                          Take string input
 l                         Move left, off the asterisk at the start of grid
  [*    ]                  Until cell is *
    ,+r_       write *, string pointer+=1, move right, write * if pointed char is last char
         [ l]ur    move left until finding a space, move up and right
               [*                                        ]     Until cell is *
                 ,                               write *
                  [   ]             until cell is [space]
                    -.               decrement string pointer, write pointed char
                       +.           increment and write string pointer
                         [         ] until cell is [space]
                           r{ d}     move right, move down until finding nonspace
                                u+.  move up, string pointer+=1 and write pointed char
                                    -.      decrement string pointer and write pointed char
                                      [   ]  until cell is [space]
                                        -.  string pointer-=1 and write pointed char
                                           { l}   move left until finding nonspace
                                               [ l]   move left until finding space
                                                   r   move right
                                                    [ u]  move up until finding space
                                                        _  write * if pointed char is last char
                                                          (if it is written, loop ends)

                                                          ' d[ d]u[ ' r] just cleanup

2

펄, 133 바이트

이것은 내 머리가 너무 힘들고 쉬워지고 예상했던 것보다 훨씬 많은 코드로 바뀌는 도전 중 하나였습니다 ... 접근법에 특히 만족하지는 않습니다. print pop@F...아마도 -n정규 표현식을 사용 하거나 사용하여 비트 를 줄일 수있는 더 좋은 방법 이지만 지금은 거기에 갈 수 없습니다 ... 원래는 사용 say하고 있었지만로 use 5.01인해 점수가 더 높아야한다고 생각 $'합니다.

@F=(/.+/g,@F)for<>;$_%=$#F,($x=length$F[$_++])<length$F[$_]&&($F[$_]=~/.{$x}/,$F[$_-1].=$',$F[$_]=$&)for 0..1e2;print pop@F,$/while@F

용법

다른 이름으로 저장하십시오 vertically-collapse-text.pl.

perl vertically-collapse-text.pl <<< 'Programming
Puzzles
&
Code
Golf'
P
Prog
&uzz
Coderam
Golflesming

2

SmileBASIC, 90 바이트

X=RND(50)Y=RND(20)G=CHKCHR(X,Y+1)<33LOCATE X,Y+G?CHR$(CHKCHR(X,Y));
LOCATE X,Y?" "*G
EXEC.

콘솔의 모든 텍스트에 중력을 적용합니다. 이것이 유효한지 또는 문자열 배열을 사용 해야하는지 잘 모르겠습니다.


1

루비, 99 82 바이트

거기에 도착...

f=->a,i=-1{a.map{|l|i+=1;(0...l.size).map{|c|a.map{|x|x[c]}.join[~i]}*''}.reverse}

시도 된 설명 :

f=->a,i=-1{a.map{|l|i+=1; # For each line `l` with index `i` in string array `a`
(0...l.size).map{|c|        # For each column `c` in `l`
a.map{|x|x[c]}.join           # Make a string of non-nil characters `c` across `a`...
[~i]                          # ...and grap the `i`th character *from the end*, if any
}*''}.reverse}              # Join the characters grabbed from each column and reverse the result

다음과 같이 실행하십시오.

a = %w[
  Programming
  Puzzles
  &
  Code
  Golf
]
puts f[a]

1

K, 30

{+{(-#x)$x@&~^x}'+x@\:!|/#:'x}

.

k){+{(-#x)$x@&~^x}'+x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"P          "
"Prog       "
"&uzz       "
"Coderam    "
"Golflesming"

설명

x@\:!|/#:'x 각 문자열을 확장하여 제곱 문자 행렬을 만듭니다.

k){x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"Programming"
"Puzzles    "
"&          "
"Code       "
"Golf       "

+ 그것을 바꾸다

k){+x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"PP&CG"
"ru oo"
"oz dl"
"gz ef"
"rl   "
"ae   "
"ms   "
"m    "
"i    "
"n    "
"g    "

{(-#x)$x@&~^x} 문자열에서 공백을 제거한 다음 문자열을 원래 길이만큼 채 웁니다.

k){(-#x)$x@&~^x}"a  b  c   de  f"
"         abcdef"

해당 함수를 바뀐 각 문자열에 적용한 다음 출력을 뒤집어 결과를 얻습니다.

k){+{(-#x)$x@&~^x}'+x@\:!|/#:'x}("Programming";"Puzzles";,"&";"Code";"Golf")
"P          "
"Prog       "
"&uzz       "
"Coderam    "
"Golflesming"

{+{(-#x)$x@&~^x}'+(|/#:'x)$x}29.
— streetster

1

pb -310 바이트

^w[B!0]{w[B=32]{vb[1]^b[0]}>}b[1]vb[1]>b[2]<[X]w[B!2]{t[T+B]b[0]>}b[0]v[T]w[X!-1]{b[1]<}b[1]vb[1]w[B!0]{w[B!0]{^w[B!0]{>}<<<<^[Y+1]w[B!0]{<}>t[B]b[0]w[B!1]{v}v<[X]w[B!0]{>}b[T]}b[0]vb[1]^w[X!0]{<vb[1]^t[B]b[0]^w[B!0]{^}b[T]w[B!0]{v}}vw[B!0]{^^w[B!0]{>}<b[0]vvw[B=0]{<}b[0]<[X]}^^>w[B=0]{vb[1]}v<<}>>^b[0]^<b[0]

정말 재앙이야 나는 그것이 어떻게 작동하는지에 대해 거의 기억하지 못한다.

pb의 입력이 작동하는 방식 (한 번에 한 줄씩)으로 인해 입력에 줄 바꿈 대신 공백을 사용해야합니다. 인터프리터가 쓰레기가 아니고 입력에 개행을 포함시킬 수있는 경우 유일한 변경 사항은 [B=32]시작이 될 때 [B=10]입니다.

프로그램 실행을보고 싶다면 비주얼을 정리하는 pbi (통역사) 업데이트를 진행하고 있습니다. 여전히 많은 작업이 필요하지만 그 동안 YouTube에서이 프로그램을 볼 수 있습니다 .


1

J, 17 바이트

-.&' '"1&.(|:@|.)

매우 즐거운 솔루션.

설명:

-.&' '"1&.(|:@|.)  input: list of strings y
              |.   reverse lines
           |:@     then transpose
-.&' '"1           remove blanks from columns
        &.         and undo the inside
           |:@|.   (that is, transpose and reverse again.)

테스트 사례 설명

   s
Programming
Puzzles
&
Code
Golf
   |.s
Golf
Code
&
Puzzles
Programming
   |:|.s
GC&PP
oo ur
ld zo
fe zg
   lr
   ea
   sm
    m
    i
    n
    g
   -.&' '"1|:|.s
GC&PP
oour
ldzo
fezg
lr
ea
sm
m
i
n
g
   |.-.&' '"1|:|.s
g
n
i
m
sm
ea
lr
fezg
ldzo
oour
GC&PP
   |.|:-.&' '"1|:|.s
P
Prog
&uzz
Coderam
Golflesming
   (-.&' '"1)&.(|:@|.)s
P
Prog
&uzz
Coderam
Golflesming
   -.&' '"1&.(|:@|.)s
P
Prog
&uzz
Coderam
Golflesming

테스트 사례

   f =: -.&' '"1&.(|:@|.)
   f
-.&' '"1&.(|:@|.)
   f >'Programming';'Puzzles';'&';'Code';'Golf'
P
Prog
&uzz
Coderam
Golflesming
   g =: [: > [: <;._1 '|'&,
   g 'Programming|Puzzles|&|Code|Golf'
Programming
Puzzles
&
Code
Golf
   f g 'Programming|Puzzles|&|Code|Golf'
P
Prog
&uzz
Coderam
Golflesming
   F =: f @ g
   F &. > 'Programming|Puzzles|&|Code|Golf' ; '1|23|456|7890' ; '1234|567|89|0'
+-----------+----+----+
|P          |1   |1   |
|Prog       |23  |52  |
|&uzz       |456 |863 |
|Coderam    |7890|0974|
|Golflesming|    |    |
+-----------+----+----+

;@;:&.(|:@|.)13
— FrownyFrog

1

사실은 13 바이트

이것은 Dennis 'Jelly answer에 설명 된 알고리즘을 사용합니다 . 입력과 출력은 모두 문자열 목록입니다. 안타깝게도 내부 목록이나 문자열의 길이가 모두 같지 않으면 내장 조옮김 함수가 제대로 작동하지 않아 처음에는 세로로 접히는 지점을 물리 칠 수 있습니다. 골프 제안을 환영합니다. 온라인으로 사용해보십시오!

R2`;i(lZ♂Σ`nR

언 골핑

          Implicit input s.
R         Reverse s.
2`...`n   Run the following function twice.
  ;i        Duplicate and flatten onto the stack.
  (l        Get the number of strings in the list.
  Z         Zip len strings together, which results in a list of lists of characters.
  ♂Σ        Sum each list of characters, which essentially joins them together.
           This function essentially transposes
R         Reverse the result.
          Implicit return.

1

라켓 312 바이트

(let((lr list-ref)(ls list-set)(sl string-length)(ss substring)(l(string-split s)))(let p((ch #f))
(for((i(-(length l)1)))(define s(lr l i))(define r(lr l(+ 1 i)))(define n(sl s))(define m(sl r))
(when(> n m)(set! l(ls l i(ss s 0 m)))(set! l(ls l(+ 1 i)(string-append r(ss s m n))))(set! ch #t)))(if ch(p #f)l)))

언 골프 드 :

(define (f s)
  (let ((lr list-ref)
        (ls list-set)
        (sl string-length)
        (ss substring)
        (l (string-split s)))
    (let loop ((changed #f))
      (for ((i (sub1 (length l))))
        (define s (lr l i))
        (define r (lr l (add1 i)))
        (define n (sl s))
        (define m (sl r))
        (when (> n m)
          (set! l (ls l i (ss s 0 m)))
          (set! l (ls l (add1 i)(string-append r (ss s m n))))
          (set! changed #t)))
      (if changed (loop #f)
          l))))

테스트 :

(f "Programming Puzzles & Code Golf")

산출:

'("P" "Prog" "&uzz" "Coderam" "Golflesming")

1

자바 스크립트 (ES6), 103 바이트

v=>(v=v.split`
`).map(_=>v=v.map((x,i)=>v[++i]?x.slice(0,n=v[i].length,v[i]+=x.slice(n)):x))&&v.join`
`

CR에서 분리 된 외부 맵을 사용하면 "중력"이 글자를 떨어 뜨릴 때까지 글자를 떨어 뜨릴 수 있도록 충분한 시간을 반복 할 수 있습니다.

내부 맵은 먼저 다음 줄이 있는지 확인하고 더 짧은 경우 다음 줄로 오버플로를 삭제합니다. 즉, 첫 번째 줄에 "ABCD"가 있고 두 번째 줄에 "FG"가 있으면 첫 번째 줄이 "AB"가되고 두 ​​번째 줄이 "FGCD"가되도록 첫 번째 줄에서 두 번째 줄로 "CD"를 삭제하십시오.

행이있는만큼 여러 번이 작업을 수행하면 문자가 원하는만큼 떨어 지므로 원하는 결과를 얻을 수 있습니다.


1

Japt , 8 바이트

y kS ù y

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

작동 원리

Uy kS ù y

Uy  Transpose at newline
kS  Replace spaces with nothing
ù   Left-pad to fit the longest line
y   Transpose at newline

z2D 문자열을 90 도의 배수로 회전시키는 것도 있지만, 문자열을 자릅니다 height > length.


7 바이트 . 그건 그렇고, Japt에 오신 것을 환영합니다 (내가 아직 당신을 환영하지 않은 경우).
— Shaggy

1

05AB1E , 10 9 바이트

¶¡RζðмζR»

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

또는 다른 시작으로 :

.BRøðмζR»

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

@ Dennis ♦ 'Pyth answer 와 비슷한 접근 방식 . @Emigna로 교체 하여
-1 바이트 .ðõ:ðм

설명:

¶¡       # Split on new-lines
  R      # Reverse the list
   ζ     # Zip/Transpose with unequal-length items (with space filler by default)
ðм       # Remove all spaces
  ζ      # Zip/Transpose unequal-length items (with space filler) again
   R     # Reverse the list again
    »    # Join the list by newlines, and output implicitly

대체 설명 :

.B      # Box (implicitly splits on new-lines and appends spaces)
   ø    # Zip/Transpose with equal-length items
        # Rest is the same

1

R, s81 52 바이트

function(x)apply(x,2,function(.).[order(!is.na(.))])

#old,longer version did the same but less efficiently
#function(x)apply(x,2,function(x){n<-na.omit(x);c(rep("",length(x)-length(n)),n)}))

나는 질문을 해석하는 데 자유를 얻었고 텍스트가 셀 당 하나의 문자가있는 행렬로 표현되어 있다고 가정했습니다.

x <- as.matrix(read.fwf(textConnection("Programming
Puzzles
&
Code
Golf"), widths=rep(1, 11)))

x는 다음과 같습니다.

     V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11
[1,] "P" "r" "o" "g" "r" "a" "m" "m" "i" "n" "g"
[2,] "P" "u" "z" "z" "l" "e" "s" NA  NA  NA  NA 
[3,] "&" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[4,] "C" "o" "d" "e" NA  NA  NA  NA  NA  NA  NA 
[5,] "G" "o" "l" "f" NA  NA  NA  NA  NA  NA  NA 

이제 NA를 사용 order하고 [열을 정렬하여 NA가 먼저 오게 한 다음 다른 모든 값을 정렬합니다.

     V1  V2  V3  V4  V5  V6  V7  V8  V9  V10 V11
[1,] "P" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
[2,] "P" "r" "o" "g" NA  NA  NA  NA  NA  NA  NA 
[3,] "&" "u" "z" "z" NA  NA  NA  NA  NA  NA  NA 
[4,] "C" "o" "d" "e" "r" "a" "m" NA  NA  NA  NA 
[5,] "G" "o" "l" "f" "l" "e" "s" "m" "i" "n" "g"

출력이 단어 여야하는 경우 더 길어집니다.

s <- (function(x)apply(x,2,function(.).[order(!is.na(.))]))(x)
s[is.na(s)]<-""
apply(s, 1, paste, collapse="")
# [1] "P"           "Prog"        "&uzz"        "Coderam"     "Golflesming"

PPCG에 오신 것을 환영합니다! OP가 형식에 문제가 없다면 안전합니다! 일반적인 방법은 질문에 대한 의견으로 질문하는 것입니다.
— JayCe

다른 질문에 대한 답변에서 언급했듯이 답변은 전체 fuinctions 또는 프로그램이어야하므로 function(x)바이트 수에 포함해야합니다.
— JayCe

1

R, 196 189 170 바이트

function(x){l=nchar;o=function(y)which(diff(l(y))<0)[1];d=function(x,i)"[<-"(x,i:(j<-i+1),c(a<-substr(x[i],1,l(x[j])),sub(a,x[j],x[i])));while(!is.na(o(x)))x=d(x,o(x));x}

사람이 읽을 수있는 버전 :

f<-function(x){
  l=nchar;

  # find the first line in x that is longer than the next line
  # if no such line exists o(x) will be NA
  o = function(y) which(diff(l(y))<0)[1]

  # d(x,i) --> clips the line i in x, adding the remainder to x[i+1]
  d = function(x,i) "[<-"(x,i:(j<-i+1),
        c(a<-substr(x[i],1,l(x[j])), sub(a,x[j],x[i])))
         # a --> clipped x[i],      sub(a,x[j],x[i]) --> expanded x[j]

  while(!is.na(o(x)))x=d(x,o(x));x
}                            

작동 방식 :

  1. 첫 번째 "나쁜"줄, 즉 다음 줄보다 긴 줄을 가져 와서 "추가"부분을 취하여 다음 줄에 추가하십시오.
  2. "잘못된"줄이 남아 있는지 확인하십시오. 그렇다면 1 번으로 가십시오.

즉, "불필요한"부분은 넘어 질 수있는 모든 것이 떨어질 때까지 쓰러집니다.

입력 : 문자형 벡터

x<-readLines(textConnection("Programming\nPuzzles\n&\nCode\nGolf"))
f(x)
# [1] "P"           "Prog"        "&uzz"        "Coderam"     "Golflesming"

0

Julia 0.6 , 141 바이트

l=length
g(z,i)=(n=z[i];m=z[i+1];(N,M)=l.([n,m]);z[i:i+1]=[n[1:min(N,M)],m*n[M+1:N]])
f(s,w=split(s),d=1:l(w)-1)=(g.([w],[d d]);join(w,"\n"))

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

로 브로드 캐스트 g.([w], [d d])하면 맵 문을 제거하고 약 7 바이트를 절약 할 수 있습니다.

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