文字列をチャンクで逆順にする


34

あなたの仕事は、数字と文字列を与えられた文字列をそのサイズのチャンクに分割し、それらを逆にするプログラムを書くことです。

ルール

プログラムは、正の整数とns印刷可能なASCIIのみ(空白を含まない)で構成される長さ少なくとも1つの文字列を受け取ります。文字列nの長さがn残りの部分で割り切れない場合、文字列はlengthのチャンクに分割される必要があります。次に、チャンクの順序を逆にして、再びまとめます。

テストケース

n   s           Output

2   abcdefgh    ghefcdab
3   foobarbaz   bazbarfoo
3   abcdefgh    ghdefabc
2   a           a
1   abcdefgh    hgfedcba
2   aaaaaa      aaaaaa
2   baaaab      abaaba
50  abcdefgh    abcdefgh
6   abcdefghi   ghiabcdef

これはなので、できるだけ少ないバイトを目指してください。


回答:





8

JavaScript(ES6)、37バイト

n=>F=s=>s&&F(s.slice(n))+s.slice(0,n)

カリー化によって入力を取得します:最初に数値、次に文字列、のようにf(2)("abcdefgh")






4

ロダ、36バイト

f n{[[_]..[try head n-1]]|reverse|_}

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

これは、1つの引数を取る関数です。文字列の文字はストリーム内にある必要があります。

tryhead関数がn-1値を読み取れない場合にエラーを破棄するために使用されます。

説明:

f n{[[_]..[try head n-1]]|reverse|_}
f n{                               } /* Function declaration */
                                     /* In a loop: */
      _                              /*   Pull one value */
           try head n-1              /*   Pull n-1 values (or less) */
     [ ]..[            ]             /*   Make an array */
    [                   ]            /*   Push it to the stream */
                         |reverse    /* Reverse all values in the stream */
                                 |_  /* Flat all arrays in the stream */
                                     /* Characters in the stream are printed */

通常ほど難読化されていません。とても美しいと思います。:)


5
プログラムをゼリーソリューションよりも読みにくくしました。
パベル

なぜではなく[[try head n]]動作しないの[[_]..[try head n-1]]ですか?
クリティキシリソス

@KritixiLithosなぜなら_式をループするからです。一度[[try head n]] n個の値を取ります[[_]..[try head n-1]]値が残っている限りn個の値を取ります。
fergusq


4

バッチ、74バイト

@if %2=="" (echo %~3)else set s=%~2&call %0 %1 "%%s:~%1%%" "%%s:~,%1%%%~3"

むしろ迷惑なことに、これは末尾再帰ではなく再帰的になります。


4

V13 10バイト

òÀ|lDÏpòÍî

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

ò      ò    ' Recursively
 À|         ' Go to the "nth" column
   l        ' Move one character right (breaks loop when no more chunks)
    D       ' Delete from here to the end of the line
     Ï      ' Add a line above the current line (now contains one chunk)
      p     ' Paste the remainder of the line that was deleted
        Íî  ' Remove all newlines

動作中:

abcdefghijkl

に変わる

efghijkl
abcd

になる

ijkl
efgh
abcd

すべての改行が削除される前


4

brainfuck、78バイト

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

入力の最初のバイトは、バイト値で指定されたチャンクサイズです。残りのバイトは文字列と見なされます。

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

展開およびコメント

Read the chunk size byte
This cell will become a counter cell
,

Move left a few cells an increment; 
this is to make the starting position 
line up with the relative positioning
needed to fit in with the loop
<<<+

While the current cell is nonzero:
[

 Move right to the first zero cell
 [>]

 Move right once and increment and then move right to the counter cell
 The increment is required because of "move to zero cell" loops
 >+>

 This loop will store one chunk of the input in consecutive memory cells
 [
  [>]   Move right until a zero cell is hit
  ,     Store 1 byte of input there
  <[<]  Move back left until a zero cell (other than the current one) is hit
  >+>-  Increment the temporary cell by 1 and decrement the counter
 ] (end loop once the counter hits zero)

 Decrement the temp cell (because we needed to have 1 there initially to make the cell location work)
 <-

 Move the temp cell to three cells after the end of the chunk
 This is the new counter cell for the next chunk
 [->>[>]>>+<<<[<]<]

 Move two cells right from where the temp cell was
 This is the first cell of the chunk; if it's 0
 then the input is finished and the loop should end
 >>
]

Due to the way the counter is kept track of the tape head
will always be four cells to the right of the last input cell
when the loops breaks
<<<<

Now the chunks are printed one by one
At the start of an iteration the tape head is at the end of a chunk
[
 Locate the start of the last chunk
 [<]>

 Print the chunk:
 [
  Print the byte held in the current cell if it isn't 1
  This is necessary because we left a stray 1 in a cell at
  the start which shouldn't be printed
  -[+.[-]]+

  Move to the next cell
  >
 ]

 Move to just left of the chunk
 <[<]

 Move three cells over to the end of the next chunk
 <<<
]

4

PowerShell、56 49バイト

mazzyのおかげで-7バイト

param($n,$s)$s-split"(.{$n})"-ne''|%{$r=$_+$r};$r

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


1)49バイト 2)コードスニペットではなく、完全なプログラムを投稿してください。確認方法 コードを拡張子付きの別のファイルに抽出し、コードの.ps1代わりにこのスクリプトを呼び出してみてください。動作する場合、テストは成功しました。
mazzy

3

Mathematica、46バイト

""<>Reverse@Partition[Characters@#2,#,#,1,{}]&

匿名関数。入力として数値と文字列を受け取り、出力として文字列を返します。ここではあまり見ません。


3

Javascript- 54 47 46バイト

リメイク:

(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()

使用されます

f=(s,n)=>s.match(eval(`/.{1,${n}}/g`)).reverse()
alert(f("abcdefgh",2));

正規表現の高速化のために@ETHproductionsに感謝します。

元の:

(s,n)=>s.match(new RegExp('.{1,'+n+'}','g')).reverse()

1
いい答えだ!eval('/.{1,'+n+'}/g')
ETHproductions

@ETHproductionsああ、はい。それが私がやろうとしていることです。私は正規表現に精通していませんでしたが!
ブルーオキリス

カレーでバイトを節約できると思いますs=>n=> ...
パベル

eval("/.{1,${n}}/g")引用符の代わりにバッククォートを使用して、でバイトを保存します。
シャギー


3

網膜、38バイト

@LeakyNunのおかげで1バイト節約

^

+`(.* (1)+¶)((?<-2>.)+)
$3$1
 1+¶

(2行目のスペースと末尾のスペースに注意してください)

このプログラムは、最初の行に入力を単項として受け取り、2行目に文字列を受け取ります。

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

テストスイート!(わずかに変更)

説明

最初のステップは、スペースを追加することです(後で重要になります)。

^
 

今度は逆になります。これは、.NETのバランスグループを使用します。ここでのグループはスタックとして機能するため、すべての一致は基本的にスタックにプッシュされることに注意することが重要です。ここで、単項数のすべての数字をグループ2にキャプチャします。文字列内の文字が見つかるたびに、グループ2から一致がポップされます。これにより、文字数が単項数を超えないようになります。

+`(.* (1)+¶)                       Capture the unary number in group 2
             ((?<-2>.)+)           Balancing group for substrings
$3$1                               Reverse

最後に、単項数と改行を削除します。

 1+¶


単項で数をとることは許容できると思います。
漏れの修道女

とにかく、あなたは置き換えることができます\d.バイトを保存します。
リーキー修道女

2番目^も冗長です。
リーキー修道女

@LeakyNunプログラムは単項式で入力を受け取るようになったため、\dもう入力する必要はありません。キャレットをゴルフで遠ざけてくれてありがとう:)
Kritixi Lithos

遅延(貪欲でない)一致を使用した33バイト
リーキー修道女

3

Java、147 138バイト

String r(String s,int n){String r="";int l=s.length();for(int i=l/n*n;i>=0;i-=n)if(!(i>=l))r+=(i+n)>=l?s.substring(i):s.substring(i,i+n);return r;}

Kevin Cruijssenのおかげで9バイト節約できました!

String r(String s,int n){String r="";int l=s.length(),i=l/n*n;for(;i>=0;i-=n)if(i<l)r+=i+n>=l?s.substring(i):s.substring(i,i+n);return r;}

展開された形式:

String r(String s,int n){
    String r="";
    int l=s.length(),i=l/n*n;
    for(;i>=0;i-=n)
        if(i<l)
            r+=i+n>=l?s.substring(i):s.substring(i,i+n);
    return r;
}

これは実際に私が初めてcodegolfを試すので、フィードバックは大歓迎です!


PPCGへようこそ!
パベル

1
こんにちは、PPCGへようこそ!これはすでにかなり良いですが、まだいくつかのゴルフのためのいくつかのint l=s.length();for(int i=l/n*n;ことがint l=s.length(),i=l/n*n;for(;あります:あなたはint 一度だけ持っていることができます。とif(!(i>=l))することができますif(l<i)。またr+=(i+n)>=l?、括弧なしでもかまいませんr+=i+n>=l?。また、まだ見たことがない場合は、Javaでのゴルフのヒントを参照して、使用するクールなゴルフのヒントをお勧めします。:)もう一度、ようこそ。
ケビンCruijssen

3

Perl 5、25バイト

-lnM5.010フラグを使用します。

say reverse<>=~/.{1,$_}/g

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

について教えてくれたグリンツへの叫び =~ m/.{1,$n}/g

-M5.010say関数の使用を有効にします。この関数は、短い名前で印刷します。

-n入力の最初の行をに入れ、末尾の改行$_-l削除します。

次に、を使用して入力の2行目を取得し、<>それを正規表現に適用します.{1,$_}:1〜$ _(最初の入力)回の間の任意の文字。これはデフォルトで貪欲であるため、常に$ _文字に一致しようとします。1,最後に可能な残りのチャンクのために必要とされています。

/g修飾子は、私たちに与えおき、その後反転して印刷されたリストとして入力文字列内のその正規表現の一致を。Perlでは、sayデフォルトでリストを渡すと、区切り文字なしでリストが結合されます。





2

QBIC、24バイト

:;[1,_lA|,a|Z=_sA,b,a|+Z

これは、最近QBICに追加した新しいサブストリング関数をうまく利用しています。

:;          Read in the cmd line params a (number) and A$ (text)
[1,_lA|,a|  Set up a FOR loop: FOR b = 1; b <= A$.length; b += a
Z=          Modify Z$; Z$ is autoprinted at the end of QBIC code
_sA,b,a|    SUBSTRING: _s is the function followed by the string 
               to take from, the starting pos and the # of chars
+Z          Take chunks from further into A$, put them before Z$



2

C、69バイト

i;f(s,n)char*s;{i=strlen(s);for(i-=i%n;printf("%.*s",n,s+i),i;i-=n);}

結果は標準出力に出力されます。


2

Scala、57 55バイト

(n:Int,s:String)=>(""/:s.grouped(n).toSeq.reverse)(_+_)

ジェイコブありがとう!それを試してみてくださいここでください

注:foldLeft( "/:")のシンボル形式を使用することで、さらに2バイトを取り出すことができました。


匿名関数にし、のmkString代わりに使用reduceLeftし、7バイトを削ります(n:Int,s:String)=>s.grouped(n).toSeq.reverse.mkString("")
ジェイコブ


2

R69 60バイト

function(s,n)cat(substring(s,(x=nchar(s):0*n)+1,x+n),sep="")

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

削除する提案をしてくれたKirill L.に感謝しseqます。


以下のように見えるこの作品はあまりにも 66のために
キリルL.

@KirillL。引数の順序を逆にすると60バイトに:なり、何らかの操作で末尾を取り除くことができます-1
ジュゼッペ

スマートでとてもいい!
キリルL.
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.