テキストのページを入れ替える


28

編集ルールの文言を修正して、暗黙的で明示的なものを作成しました。また、明らかな混乱のいくつかのポイントを明確にするためにいくつかの強調を追加し、関数の代わりにスタンドアロンプ​​ログラムを作成するオプションを明示的に定義しました。

ここでの目標は、テキストファイル(または文字列)を取得し、行を列に、またはその逆に転置する関数を作成することです。

例:

私はテキストです。
転置して
それできますか?

結果:

これは、C
 ら
あん
mn
 sy
アポ
 ou
ts
ええ
XO
tm
.ei
 .t
  ?

ルール:

  • あなたは、使用される唯一の空白文字があると仮定することは許可されている" "と"\n"し、任意の行には、末尾の空白が存在しないこと。
  • ファイルはASCIIであると想定できます。使用するエンドラインマーカーはユーザー次第です(CRLFまたはLF)。これは一例で正しく動作しなければならないが、それはまた、上で動作するはずの任意満たす上記の仮定することを入力。
  • 列の行を維持するために、スペースがない場合(例のように)を挿入する必要がある場合があります。
  • 結果のどの行にも末尾の空白があってはなりません。
  • 最後の改行文字(最後の行)はオプションです。
  • 関数または完全なプログラムでなければなりません。関数が文字列を受け入れる場合、結果を文字列として返す必要があります。ファイル名を受け入れる場合、結果を保存したファイルの名前を返します。さらに、STDINからの入力を受け入れ、正しい結果をSTDOUTに出力する完全なプログラムを作成できます。これを行う場合、STDERRに何も出力しないでください。
  • 最短の手順で勝ちますが、私は好きな答えを投票します。

規則に基づいて、例の出力は、最終改行が含まれるかどうかに応じて、53または52バイト(LF改行の場合)の長さです。

注:特定の要件ではありませんが、連続して2回実行される関数が元の関数と同一ではない場合(最終的な改行が異なる場合があり、ファイルの最後の空行が削除されます)、おそらくルールの1つを破っています。


言語組み込みの禁止を解除することにしました。
— ティムセギーン14年

末尾の空白条件を明確にするために編集しました。
— ティムセギーン

機能を求めていますか?STDINから文字列を受け取り、正しい出力をSTDOUTに出力することは受け入れられますか?
— ジャスティン14年

@Quincunxはい、私はそれを「関数」として受け入れています。その点で明示的にルールを変更します。
— ティムセギーン14年

テキストの転置関数は、末尾のwsを許可しない限り、インボリューションにはなりません。例: "a * c \ ndef \ n"-> TT-> "a * \ ncd \ nef \ n"〜 "a \ ncd \ nef \ n"-> TT-> "acd \ nef \ n"、ここで* = ws
— エマニュエルランドホルム14年

回答:



4

J(31 40)

f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'

これは、文字列を受け取り、文字列を返す関数です(つまり、マトリックスではなく、適切な場所に改行が挿入された文字ベクトル)。

編集:どの行にも末尾の空白はありません。

テスト:

   f=:3 :';(,&LF@dlb&.|.)&.><"1|:>LF cut y'

   string=:stdin''
I am a text.
Transpose me.
Can you do it?
^D

   $string
42
   $f string
53
   f string
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

組み込みの禁止を解除したことに気づいたことを願っています。
— ティムセギーン14年

@Tim:はい、そうでなければ私はこれを投稿しなかったでしょう。
— マリヌス14年

末尾の空白ルールは不明瞭に書かれていますか?あなたは私が予想したよりも多くのキャラクターを持っているようです。
— ティムセギーン14年

何人のキャラクターが必要ですか?文字列の最後の文字は?\nです。
— マリヌス14年

1
@Tim:APLでは44までしか取得できませんでした。主な理由は、APLがどちらもcutまたはdlbデフォルトで提供せず、APLでさえ自分で書くと多くの文字が必要になるからです。
— マリヌス14年

4

ルビー111

ゴルフ:

def f t;s=t.lines;s.map{|l|l.chomp.ljust(s.map(&:size).max).chars}.transpose.map{|l|l.join.rstrip+?\n}.join;end

ゴルフをしていない:

def transpose_text(text)
  max_length = text.lines.map(&:size).max
  text.lines.map do |line|
    line.chomp.ljust(max_length).chars
  end.transpose.map do |chars|
    chars.join.rstrip + "\n"
  end.join
end

Rubyには配列転置関数があるため、これは単に行をパディングし、文字の配列に変換し、RubyのArray#transpose関数を使用してから、文字の配列を行に戻します。

単純に1文字の識別子を使用し、スペースを削除し、text.linesに一時的なものを使用し、max_lengthの計算をインラインで実行しました(効率性のためのポイントはありません)。


いいね あなたは置き換えることによって、1つの以上の文字を取り除くことができ"\n"て?\n。
— OI

また、.to_aは不要です。そこにさらに5文字を追加できます。
— OI

@OIありがとう、私はあなたに6人のキャラクターを借りています。1.9.3を使用する職場でこれを打ち切りました。to_aは1.9.3で必要ですが、2.0では必要ありません。
— ウェインコンラッド14年

そうですか。知っておくといい。RubyでいくつかのStringメソッドを示してくれたとしても、もっと頻繁に使用することを検討してください。乾杯!
— OI 14年

2
コードゴルフの課題のいくつかは、ルビーの学習に対する私の興味を新たにしました。
— ティムセギーン14年

4

R、171

function(e){p=strsplit
x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t)))
x[is.na(x)]=" "
cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")}

使用例:

text <- "I am a text.
Transpose me.
Can you do it?"


(function(e){p=strsplit
x=t(plyr::rbind.fill.matrix(lapply(p(p(e,"\n")[[1]],""),t)))
x[is.na(x)]=" "
cat(apply(x,1,function(y)sub(" *$","",paste(y,collapse=""))),sep="\n")})(text)

ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?

末尾の空白は削除されます。


4

Python 2.7(97 79 94 90)

編集:機能要件を逃しました。

私はここの初心者のようなものであるため、これは改善されると確信していますが、最初はそうです。

c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))

このコードは、単純なsplit文字列を使用して行のベクトルに分割します。次にmap、関数値としてNone(ユニティ関数)およびzip_longestsplat 演算子を使用して、ベクトルを転置およびパディングします(Python3 と同様の機能)

残りのコードは、Noneスペースにマップし、マトリックスをトリミングして、単一の文字列に再度組み立てます。

>>> a = 'I am a text.\nTranspose me.\nCan you do it?'
>>> c(a)                                                                            
'ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n  ?'
>>> len("""c=lambda a:'\n'.join(''.join(y or' 'for y in x).rstrip()for x in map(None,*a.split('\n')))""")
88
# (+2 since `\n` is considered by `len` to be a single char)

厳密に準拠していません。関数は文字列を受け取り、文字列を返します。
— ティムセギーン14年

@Timはい、見逃しました。今修正、ありがとう。
— ヨアヒム・イザクソン14年

+1は、現時点で最短の準拠Pythonエントリのようです。
— ティムセギーン14年

のいい使い方map。私はそれを使用する場所を探し続けています...あなたは私にそれを打ち負かしました。;)
— ブースビー14年

4

Bash + coreutils + sed、83

eval paste `sed 's/.*/<(fold -w1<<<"&")/'`|expand -t2|sed 's/\(.\) /\1/g;s/ \+$//'

foldそしてpaste重要な仕事をします。残りは単なる書式設定です。

stdinからの入力を受け入れ、stdoutに出力します。

$ < tr.txt ./transposefile.sh
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
$ < tr.txt ./transposefile.sh | ./transposefile.sh
I am a text.
Transpose me.?
Can you do it
$ 

「結果には、行の末尾に空白があってはならない」というルールに違反しているように見えます。
— ティムセギーン14年

@TimSeguineおっと、私はそれを見逃しました。最新の編集で修正しました。
— デジタル外傷14年

3

C(278バイト)

編集:これは実際にはルールを破ります。ファイル名を引数として受け取りますが、stdoutに書き込むためです。後で編集してファイルに書き込み、ファイル名を標準出力に出力します。

これは私の初めてのコードゴルフですので、慈悲を持ってください。普通の古いC.入力test.txtを入れて実行させます!

clang transpose.c -o transpose && ./transpose test.txt

#import <stdio.h>
#import <stdlib.h>
#import <string.h>

#define BUFFER_SIZE 1024

#define MAX(A,B) ((A)>(B)?(A):(B))

int main(int argc, char **argv) {
    char line[BUFFER_SIZE];

    FILE *f; int nLines, maxLen;

    f = fopen(argv[1], "r");
    while(!feof(f) && fgets(line, BUFFER_SIZE, f)) {
        nLines++;
        maxLen = MAX(maxLen, strlen(line));
    }
    fclose(f);

    for (int charPos = 0; charPos < maxLen; charPos++) {
        f = fopen(argv[1], "r");
        for (int linePos = 0; linePos < nLines; linePos++) {
            fgets(line, BUFFER_SIZE, f);
            printf("%c", charPos < strlen(line) && line[charPos] != '\xA' ? line[charPos] : ' ');
        }
        printf("\n");
        fclose(f);
    }

    return 0;
}

短い変数名を使用し、不要なフォーマットを削除し、ファイルハンドルのリークを許可し、すべての警告を無効にすることにより、これは278バイトに削減されます。(これは暗黙的なインポートを使用するため、すべてのシステムで適切にリンクされない可能性があります。私のマシンで動作します!)

#import <stdio.h>
int main(int C,char**V){char L[1024];int A,B,D,I,J,*F=fopen(V[1],"r");while(!feof(F)&&fgets(L,1024,F)){A++;D=strlen(L);B=B>D?B:D;}for(I=0;I<B;I++){F=fopen(V[1],"r");for(J=0;J<A;J++)fgets(L,1024,F)&&printf("%c",I<strlen(L)&&L[I]!='\n'?L[I]:' ');printf("\n");}}

暗黙の利点を利用しintて宣言の一部を短縮できると思いますか、それとも今では違法ですか?
— ティムセギーン14年

ええ、私はstdlib.hまたはstring.hをインポートしないために、後の編集でそれを使用しています。stdio.hをインポートしないと、実行時にセグメンテーション違反が発生します。
— wjl 14年

ルールに関するコメントを編集するには、別の方法として、stdinからの入力を受け入れる方法があります。適合していると考えます。また、一見しただけではわかりません。転置バージョンの行末から空白を削除しますか?
— ティムセギーン14年

RAMに保存しないようにファイルを複数回再読み取りするため、stdioからの読み取りはおそらく困難になります。:)どの空白を削除すべきかわかりません。今のところ、残念ながら、それはまったくストリッピングしないと思います。私もそれに取り組む必要があります。
— wjl 14年

キーワードA,B,D,I,J,*Fを回避するために、グローバル変数として宣言できますint。同様に、宣言と引数intから削除できます。では、多くの場所でオプションです。mainCCint
— コンラッドボロスキー14年

3

AutoHotkey 210

f(i){
StringSplit,o,i,`n
m:=0
loop % o0 {
a:=A_index
if (t:=Strlen(p:=o%a%))>m
m:=t
StringSplit,l%a%,o%a%
}
loop % m {
a:=A_index,n:=""
loop % o0
n.=(j:=l%A_index%%a%)=""?" ":j
s.=Rtrim(n," ") "`n"
}
return s
}

テスト

text=
(
I am a text.
Transpose me.
Can you do it?
)
msgbox % f(text)

これをテストすることはできませんが、準拠しているように見えます
— ティムセギーン14年

3

Ruby:88文字

(他のRubyソリューションよりも短いので投稿しました。私のコードがそれらに比べて新しいものを導入するかどうかはチェックしていません。すでにRubyソリューションを投稿していて、これがほとんどあなたのコピーであると感じたら、コメントしてください、私は答えを廃止します。 )

f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/}

サンプル実行:

irb(main):001:0> f=->t{l=t.split$/;r=[""]*m=l.map(&:size).max;l.map{|l|m.times{|i|r[i]+=l[i]||" "}};r*$/}
=> #<Proc:0x99a9e68@(irb):1 (lambda)>

irb(main):002:0> sample='I am a text.
irb(main):003:0' Transpose me.
irb(main):004:0' Can you do it?'
=> "I am a text.\nTranspose me.\nCan you do it?"

irb(main):005:0> puts f[sample]
ITC
 ra
aan
mn
 sy
apo
 ou
ts
eed
x o
tm
.ei
 .t
  ?
=> nil

irb(main):006:0> puts f[f[sample]]
I am a text.
Transpose me.
Can you do it?
=> nil

+1いずれの場合でも、より良くゴルフできました。
— ティムセギーン14年

3

バッシュ、124バイト

D=`mktemp -d`;split -l1 - $D/;for F in $D/*;do grep -o . $F>$F+
done;paste $D/*+|sed -e's/\([^\t]\)\t/\1/g;s/\t/ /g;s/ *$//'

標準入力を読み取り、標準出力を書き込みます。それを試してみてください:

echo $'I am a text.\nTranspose me.\nCan you do it?' | script.sh

使い方:

  • split単一行への入力(一時ディレクトリ内のファイル$D)
  • grep(files * +)を使用して行を単一の文字に分割します
  • paste(TABで区切られた列)を使用して文字を並べてレイアウトする
  • 配置TABを削除し、フィラーTABを空白に置き換え、トリムを使用して sed

編集:

  • -9:整理コードを削除 ;rm -r $D(Timに感謝)
  • -2:サフィックスの+代わりに使用_して短縮${F}_して$F+
  • -3:L分割結果ファイルからプレフィックスを削除

コードゴルフの目的のために、あなたは必ずしもあなた自身の後に素敵できれいにする必要はありません。rm文字数を少し減らすことができます。
— ティムセギーン14年

2

ルビー— 144文字

これがゴルフの私の最初の試みです。

def f t
t.split(?\n).each{|l|l<<' 'until l.size==t.split(?\n).map(&:size).max}.map{|x|x.split('')}.transpose.map{|l|l.join.rstrip}.join(?/n)
end

出力のputs f text場合textは、上記のルールに従って複数行の文字列をwhere で実行します。未使用バージョンは以下のとおりです。

def text_transpose(text)
  lines = text.split(?\n)
  maxlen = lines.map(&:size).max
  lines.each { |line| line << ' ' until line.size == maxlen }
       .map  { |line| line.split('') }.transpose
       .map  { |char| char.join.rstrip }.join(?\n)
end

Rubyで同様の、しかし最終的にはより良いソリューションについては、上記のWayne Conradのコードをご覧ください。


私はtranspose私のものを書く前にあなたの答えに気づかなかった。私があなたの答えを本質的に書き直したことは、それほど良いことではないようです。:(
— ウェインコンラッド14年

2
まったく気にしません。コードを独自に思いついたので、それはレースではありません。私は間違いなくあなたのソリューションから何かを学びました。私がを使用していたためにあなたが遠慮していたらtranspose、より良いRubyソリューションが浮上しなかった可能性があります。プログラミングで私が最も気に入っていることの1つは、アイデアを協力して他家受粉する意欲です。再び会うまで、親切な先生。乾杯!
— OI

2

PHP 194

function x($a){$a.="\n";$s=strlen($a);$i=0;while($c<$s)if($a{$c}!="\n")$b[$i++].=$a{$c++};else{$c++;for(;$i<$s;$i++)$b[$i].=" ";$i=0;}ksort($b);return rtrim(implode("\n",array_map("trim",$b)));}

ゴルフ以外:

function x($a) {
    $a.="\n";
    $s=strlen($a);
    $i=0;
    while($c<$s)
        if($a{$c}!="\n")
            $b[$i++].=$a{$c++};
        else{
            $c++;
            for(;$i<$s;$i++)
                $b[$i].=" ";$i=0;
        }
    ksort($b);
    return rtrim(implode("\n",array_map("trim",$b)));
}

これは私の最初のゴルフの試みですので、親切にしてください!また、ヒント/提案は大歓迎です!


それは私のPHPの試みよりも短いです。"sを削除することで2つのキャラクターを保存できます"trim"。phpは警告を出しますが、うまく機能します。
— ティムセギーン14年

@TimSeguine警告は画面上に正しく出力されますか?@警告を抑制するために使用する必要があります。
— ericw31415

@eric私はしばらく活動していないので意見が変わったかもしれませんが、過去には無関係なデータを標準エラーに出力することは受け入れられると考えられていました。
— ティムセギーン16

許されますか?それが本当なら、私はそれを知りませんでした。
— ericw31415

2

MATHEMATICA 117文字

t = "I am a text.\nTranspose me.\nCan you do it?";

f=(m=Length/@(f=Flatten[Characters/@StringSplit[#,"\n"],{{2},{1}}])//Max;
StringJoin@@@(PadLeft[#,m," "]&/@f)//Column)&

私はこれをテストすることはできませんので、行の終わりにあるトレース空白を削除することを確認できますか?また、これは(一見)ルールを必要とする関数を定義するために表示されません。
— ティムセギーン14年

こんにちは@Tim、今では関数fです!.. tks-
— ムルタ

2

Perl(92 + 1)

stdinを読み取り、stdoutに書き込みます。のスコアに1を加えるsay

@L=map[grep!/\n/,split//],<>;do{$_=join'',map shift@$_||$",@L;s/ +$//;say}while grep@$_>0,@L

2

CJam、32 25バイト

CJamはこのチャレンジよりも新しいため、この回答は受け入れられません。

user23013によってかなり短縮されました。

qN/_z,f{Se]}z{S+e`);e~N}%

ここでテストしてください。

qN/                       "Read input, split into lines.";
   _z,                    "Transpose, get length (find maximum line length).";
      f{Se]}              "Pad each line to that length with spaces.";
            z             "Transpose.";
             {         }% "Map this block onto each line in the result.";
              S+          "Add a space to ensure there's at least one.";
                e`        "Run-length encode.";
                  );      "Discard the trailing run of spaces.";
                    e~    "Run-length decode";
                      N   "Push a newline.";

適格かどうか、それは素晴らしい遅い答えです。この答えの最も難しい部分は、末尾のスペースを扱うことだったようです。
— ティムセギーン

@TimSeguine確かに。組み込みのトリミング演算子がなければ、CJamでこれを手動で行うのは驚くほど面倒です(user23013の提案はすでにかなり改善されています)。
— マーティンエンダー

2

Javascript、103

s=>[...s].map((_,i)=>s.split`
`.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?`
`:q)).join``

少ないゴルフ

s=>[...s].map(
     // we need 'i' ranging from 0 to the length of the longest input line
     // so we scan all the input string, that is surely longer
     // but we need to check that after some point the output must be empty
     (_, i) => ( 
       r = '', // the current output row, starts empty
       q = '', // flag to check if we are beyond the longest line
       s.split('\n') // split in rows
       .map( 
         b => ( // for each input row in b
           q = b[i] || q, // if there is a char at position i in b, i goes to q
           r += b[i] || ' ' // add to output the char at position i or a fill space
         )
       ),
       q // if q is still '', we are beyond the longest input line 
       ? r.replace(/ *$/,`\n`) // trim leading space and add newline
       : '' // no output 
     )
   ).join('')

テスト

F=
s=>[...s].map((_,i)=>s.split`
`.map(b=>r+=b[q=b[i]||q,i]||' ',r=q='')&&r.replace(/ *$/,q?`
`:q)).join``

function go() {
  var text=I.value
  var output = F(text)
  O.textContent = output
}

go()
#I { width:50%; height:5em }
<textarea id=I>I am a text.
Transpose me.
Can you do it?</textarea><br>
<button onclick='go()'>Transpose</button>
<pre id=O></pre>



2

Perl 5バイト

これはANSIエスケープシーケンスを使用しているため、TIOでは動作しないことに注意してください。ただし、ここで実際に動作を確認できます。。。

$"="[1D";$_="[1;$.H@F"

説明

このコードは、最初にリスト区切り記号($")の値を垂直タブに変更し、続いて「後方に1列進む」ためのANSIエスケープシーケンス(\x1b[1D)を変更し、次に暗黙的に出力される変数$_をANSIエスケープシーケンスで始まる文字列に設定します「1行目$.($.現在のテキスト行)から印刷を開始する」(\x1b1;$.H)の場合、リスト@F(その行のすべての文字のリストで、autosplit(-a)によって空の分割パターン(-F)が挿入されます)のコンテンツを配置します$"前の文字の後に出力を続けるのではなく、カーソルを垂直に下に移動して、各アイテムの間にます。

オンラインでお試しください!


1
なんてこった、本当に恐ろしい!大好きです!
— ティムセギーン

1

C ++(243文字)

文字列を受け取って返す関数は次のとおりです。

私は数十個の文字を剃ることができましたが、愚かではないコード(高速で実行され、大丈夫です)として保持することにしました。たぶん、これが初めてのコードゴルフだからです。私はまだハードコアではありません:)

string f(string s){stringstream ss(s);vector<string> v;for(size_t i=0;getline(ss,s);++i){if(v.size() < s.size())v.resize(s.size());for(size_t j=0;j<s.size();++j){v[j].resize(i,' ');v[j].push_back(s[j]);}}s="";for(auto& i:v)s+=i+'\n';return s;}

フォーマットあり:

string f(string s)
{
    stringstream ss(s);
    vector<string> v;

    for(size_t i = 0; getline(ss, s); ++i)
    {
        if(v.size() < s.size())
            v.resize(s.size());

        for(size_t j = 0; j < s.size(); ++j)
        {
            v[j].resize(i, ' ');
            v[j].push_back(s[j]);
        }
    }

    s = "";
    for(auto& i : v)
        s += i + '\n';

    return s;
}

を使用すると仮定しますusing namespace std;。
— コンラッドボロフスキ14年

@xfix通常はありませんが、私はこれを行いました
— デビッド

1
私がうるさい場合はusing namespace std;、文字数に追加する必要があります。
— ティムセギーン14年

1

Python 2.7-115文字:

ワンライナー:

>>> a
'I am a text.\nTranspose me.\nCan you do it?'

>>> "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])
'ITC\n ra\naan\nmn \n sy\napo\n ou\nts \need\nx o\ntm \n.ei\n .t\n  ?\n'

よりきれいな印刷で:

>>> print "".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])
ITC
 ra
aan
mn 
 sy
apo
 ou
ts 
eed
x o
tm 
.ei
 .t
  ?

115文字で:

>>> len(""""".join(["".join(i)+'\n' for i in zip(*[x+" "*(len(max(a.splitlines(), key=len))-len(x)) for x in a.splitlines()])])""")
115

ルールが要求するように、行の末尾の空白を削除していません。
— ティムセギーン14年

また、実際には116バイトで、単一の文字\nと見なされますが、len2文字です:)
— ヨアヒムイサクソン14年

1
UNIXの@JoachimIsaksson \nは1つです。だから、私は1つがいいと言います。
— ティムセギーン14年

@Tim len("\n")は1を表示しますが、ソースコードでは確かに2つの独立した文字です。ソースをファイルに保存すると、lsディスプレイ116 が表示lenされます。測定前にエスケープ文字が処理されるため、コードサイズを測定する最善の方法ではないというだけで、:)
— Joachim Isaksson 14年

@JoachimIsakssonああ、ごめんなさい、あなたの主張を誤解しました。
— ティムセギーン14年

1

GolfScript、51文字

n%.{,}%$-1=" "*:y;{y+y,<}%zip{n\+0{;).32=}do}%((;\+

これは最初の試みです。改善できると思います。ほとんどのコードは、パディングおよび後続スペースの削除要件に準拠することです。n%zip n*ことです。も十分です。

追伸 次の46文字バージョンは、指定されたサンプル入力に対してジョブを実行しますが、入力列がすべてスペースで構成されている場合はクラッシュします。

n%.{,}%$-1=" "*:y;{y+y,<}%zip{0{;).32=}do]}%n*

チャレンジが明示的にそうではないとしても、それで失格となるのに十分だと思います。


あなたの仮定は正しいです。ルールで許可されている前提の下で、ASCIIテキストで動作するはずです。
— ティムセギーン14年

1

スキーム/ラケット113

テキスト:

(define t (list 
    (string->list "I am a text.") 
    (string->list "Transpose me.")
    (string->list "Can you do it?")
))

新しい行と余分な空白なし:

(define s(λ(v x)(if(= x 0)'()(cons(list->string(car v))(s(cdr v)(- x 1))))))(s(apply map list t)(length(car t)))

ユーザーフレンドリーなバージョン

(define text (list 
    (string->list "I am a text.") 
    (string->list "Transpose me.")
    (string->list "Can you do it?")
))

(define transpose
    (λ(text length)
        (if (= length 0)
            '()
            (cons (list->string (car text)) (transpose (cdr text) (- length 1)))
)))

(transpose (apply map list text) (length (car text)))

1

ハスケル

import Data.List
main = interact (unlines . transpose . lines)

短いので、空白を追加する必要がありました...


ここで空白の一部を削除できると確信しています。しかし、そうでなければ、素晴らしいソリューション。
— コンラッドボロスキー14年

3
これは私のシステムではまったく機能しません。コメントに表示するのは少し難しいですが、2回実行するとが表示されますI am a text..? Transpose met Can you do i。
— マリヌス14年

ええ、例のように列を無傷に保つために行をパディングしていないのではないかと考えています。Theorectally、関数の実行結果は、二回(おそらく付加または最後の改行の除去と)元の文字列でなければならない
— ティムSeguine

1

Pythonの89 103の文字

def f(a):return'\n'.join([''.join(i).rstrip()for i in zip(*[j+' '*99 for j in a.split('\n')])]).rstrip()

汚い。工業用強度バージョンでは90 104文字。:^)


not a function.
— Tim Seguine

@Tim My bad, fixed. Anyway my solution is inferior to Joachim Isaksson's. I wonder if there's any short way to solve this problem with recursion.
— TrevorM

1

Mathematica, 95 chars

f=""<>Riffle[Thread@PadRight@Characters@StringSplit[#,"\n"]//.{0->" ",{x___," "..}:>{x}},"\n"]&

1

K, 56

This should meet the spec now.

Accepts a string, returns a string.

{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x}

.

k)f:{`/:{$[" "=*|x;|(+/&\" "=|x)_|x;x]}'x@'/:!max@#:'x:`\:x}
k)f"I am a text.\nTranspose me.\nCan you do it?"
"ITC\n ra\naan\nmn\n sy\napo\n ou\nts\need\nx o\ntm\n.ei\n .t\n  ?\n"
k)f f"I am a text.\nTranspose me.\nCan you do it?"
"I am a text.\nTranspose me.\nCan you do it?\n"

The output appears to be an array of strings?
— Tim Seguine

@Tim It is. If you want a single string then add three chars. {`/:x@'/:!max@#:'x:`\:x} for 26.
— tmartin

You also have a problem with trailing whitespace. And "If it accepts a filename, then you return the name of the file where you saved the result." You need to return output in the same manner you accept input.
— Tim Seguine

@Tim should be fixed now. Kills my bytecount though
— tmartin

I suspected it might :( , but a spec is a spec.
— Tim Seguine

1

Groovy, 98 chars

{i->o=[].withDefault{''};i.readLines().each{it.toList().eachWithIndex{c,d->o[d]+=c}};o.join('\n')}

online

ungolfed:

{i->
o=[].withDefault{''};//create list with empty string as default value 
i.readLines()
.each{
    it.toList() //split every line to characters
    .eachWithIndex{ 
        c,d->o[d]+=c //append to string from list with right index
    }
};
o.join('\n')}//join list with newlines
}


1

J, 28 26 Bytes

Saved 2 bytes thanks to frownyfrog

t=.,@:(,&LF"1)@|:@:>@cutLF

Takes a string, returns a string. I'm not sure if there's a shorter version of the 'cutopen' function verb that I could use.

There's also the shorter

t=.|:@:>@cutLF

But I'm not sure it falls within the OP's guidelines, as it returns an array of characters.

How it works:

                     cutLF   | Splits the input on new lines and boxes them
                    @        | Composes verbs (as does @:, but they're not equal)
                   >         | Unboxes this, forming an array of the lines
                 @:          |
               |:            | Transposes the array
      (      )@              |
       ,&LF                  | Appends a new line...
           "1                | To each row of the array
    @:                       |
   ,                         | Flatten the result
t=.                          | Assign this verb to t

The other version works the same, but doesn't convert the transposed array to a properly formatted string.

Examples:

NB. Define a multi-line string

    text =: 0 : 0
I am a text.
Transpose me.
Can you do it?
)

    t text
ITC
 ra
aan
mn    NB. There's whitespace after the 'n' here, but I assume it doesn't count as trailing since it's part of the original string
 sy
apo
 ou
ts 
eed
x o
tm 
.ei
 .t
  ?

    t t text
I am a text.     NB. Again, whitespace here, but it's part of the argument of the second 't' (added by the first 't' to keep columns straight)
Transpose me. 
Can you do it?

I would use cutLF.
— FrownyFrog

1
Save 1 character with 0|:>@cutLF
— FrownyFrog

1

Lua, 203 189 bytes

t={{}}i=1m=0(...):gsub(".",function(c)n=#t[i]if c=="\n"then i=i+1t[i]={}else t[i][n+1]=c end m=m<=n and n+1or m end)
for x=1,m do for p=1,i do io.write(t[p][x]or" ")end _=m<=x or print()end

Try it online!

I saw another Lua solution here, but I don't think there's a problem with posting 2 solutions on the same language. If there is, tell me :)


1
There's nothing wrong with multiple answers in the same language. Even identical answers are allowed to an extent (though it's encouraged to at least check if you're posting the a similar solution)
— Jo King

Unfortunately Your result must not have trailing whitespace on any line.
— Jo King

But I can't see trailing whitespaces on the output of my code. There's no spaces after the line ends and no blank line at the end.
— Visckmart

The part that seems to catch people out is on any line. e.g. This has extra whitespace on the second line
— Jo King

Ohhh now I got it! Sorry. I'll try to make it work as soon as I have time. I think the problem was that there's only 1 example test and I thought that would be the "stress" test hahah But ok, thanks for telling me :)
— Visckmart
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.