そこで、私はそれを修正しました(テープで)


41

チャレンジ:

大文字と小文字のどちらか(またはどちらか)のみを含む文字列を指定して、tape水平に配置して修正します。私たちは、アルファベットの二つの隣接する文字(ラップアラウンドを無視してのみ前進)の違いを確認し、そして同じくらいにスペースを充填することによって、これを行うTAPE/ tape私たちが必要となるよう。


例:

入力:abcmnnnopstzra
出力:abcTAPETAPETmnnnopTAstTAPETzra

どうして?

  • cmする必要がありますdefghijkl(長さ9)ので、我々がこれを埋めますTAPETAPET
  • between pと(length 2)であるs必要があるqrため、これをTA;で埋めます。
  • Between tと(length 5)であるz必要があるuvwxyため、これをで埋めTAPETます。

チャレンジルール:

  • 違いは前方にのみ適用されるため、間にテープはありませんzra
  • のような同じ隣接する文字を複数持つことが可能nnnです。
  • 合理的な形式で入力を行うことができます。単一の文字列、string-array / list、character-array / listなどにすることができます。出力には同じ柔軟性があります。
  • 任意の方法で小文字および/または大文字を使用できます。これは、入力、出力、およびの両方に適用されますTAPE
  • 不要TAPEである可能性があります。その場合、入力は変更されません。

一般的なルール:

  • これはであるため、バイト単位の最短回答が優先されます。
    コードゴルフ言語では、非コードゴルフ言語で回答を投稿しないようにしてください。「任意の」プログラミング言語の可能な限り短い答えを考えてみてください。
  • 回答には標準の規則が適用されるため、STDIN / STDOUT、適切なパラメーターと戻り値型、完全なプログラムを持つ関数/メソッドを使用できます。あなたの電話。
  • デフォルトの抜け穴は禁止されています。
  • 可能であれば、コードのテストへのリンクを追加してください。
  • また、必要に応じて説明を追加してください。

テストケース:

Input:  "abcmnnnopstzra"
Output: "abcTAPETAPETmnnnopTAstTAPETzra"

Input:  "aza"
Output: "aTAPETAPETAPETAPETAPETAPEza"

Input:  "ghijk"
Output: "ghijk"

Input:  "aabbddeeffiiacek"
Output: "aabbTddeeffTAiiaTcTeTAPETk"

Input:  "zyxxccba"
Output: "zyxxccba"

Input:  "abccxxyz"
Output: "abccTAPETAPETAPETAPETAPExxyz"

Input:  "abtapegh"
Output: "abTAPETAPETAPETAPETtaTAPETAPETAPETApeTgh"

Input:  "tape"
Output: "taTAPETAPETAPETApe"

10
修正の間にいくつかを破棄する理由がわからない(たとえば、TAPETAPETで修正した後、TAで修正する前にAPEを破棄する)は、私にとっては良いTAPEの無駄のように思えますが、たぶん私はそれをロールバックします(ごめん)。
ジョナサンアラン

@JonathanAllan Hehe、それはちょっと「テープ」の無駄だということは確かに正しい。うーん、チャレンジのパート2で使用するかもしれません。;)
ケビンクルーイッセン

文字列がテープに付属している場合はどうでしょうか-abTAPEghなど?
マナセカッツ

@manassehkatzこれは、他のすべての文字として解釈されるため、さらに読みやすくするためにab[TAPETAPETAPETAPET]TA[TAPETAPETAPETA]PE[T]gh追加されました[]
ケビンクルーイッセン

1
@KevinCruijssen一貫性はありますが、(「テープを無駄にする」質問のように)100%論理的ではありません。おそらくもう1つのテストケース:入力TAPE、出力TATAPETAPETAPETAPE(私はそれが正しいと思います...)
manassehkatz-Reinstate Monica

回答:


8

05AB1E14 12バイト

'¡ÉIÇ¥<∍‚ζJJ

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

説明

'¡É            # push the string "tape"
   I           # push input
    Ç          # convert to a list of character codes
     ¥         # calculate deltas
      <        # decrement
       ∍       # extend the string "tape" to each of these sizes
               # results in an empty string for sizes smaller than zero
        ‚ζ     # zip with input (results in a list of pairs)
          JJ   # join to a list of strings and then to a string

4
説明を追加しますか?私はそれがゼリーの答えにかなり似ていると思いますが、どの文字が結果を得るためにどの操作に使用されるのか興味があります。私の課題の一般的なルールの1つ:「また、必要に応じて説明を追加してください。」、Jelly、05AB1E、Charcoal、APLなどの言語では、ほとんどの人が読むことができず、説明が必須であると仮定しても問題ありません。:)
ケビンクルーイッセン

@KevinCruijssen:確かに。通常、私は05AB1Eの回答に説明を追加しますが、投稿する時間がない場合があります。
エミグナ

1
-d説明の代わりに何が行われているかの生スタック操作ごとのダンプを取得するために追加できる05AB1E TIOリンクの引数に@KevinCruijssenがありますが、私もそれらを投稿しようとしていますが、特に簡単ではありません私のLOLの。
魔法のタコ

10

ゼリー、13バイト

OI’“¡ʂƁ»ṁ$€ż@

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

説明

OI '“¡ʂƁ»ṁ$€ż@ –フルプログラム。コマンドライン引数として文字列を取ります。
O –序数。各文字のASCII値を取得します。
 I '–増分(デルタ)を取得し、それぞれから1を引きます。
          €–それぞれの違いについて...
   「¡ʂƁ»ṁ$ –これらの値に従って圧縮文字列「テープ」を成形します。
                基本的に「テープ」を必要な長さまで延長/短縮します。
           ż@ –入力とインターリーブします。

12に下げるためのコツは次の
ジョナサンアラン

@JonathanAllanそれは私には無効のようです。のabctapetapetmnnnopapstetapezra代わりに出力しますabctapetapetmnnnoptasttapetzra
ミスターXcoder

7
ああ、それは無効です-ロールからテープを無駄にすることに気付いていませんでした!
ジョナサンアラン

7

Haskell、58バイト

f(x:y:r)=x:take(length[x..y]-2)(cycle"TAPE")++f(y:r)
f s=s

オンラインでお試しください!関数は、f連続した文字の文字列とルックスの上に再帰xycycle"TAPE"無限の文字列を生成します"TAPETAPETAPE..."[x..y]からxまでの文字の範囲を取得するyため、長さから2を引く必要があります。x後でアルファベットで発生する場合、yまたは両方が同じ文字である場合、減算後に負の数を取得しますが、幸いにもtakeそれらを受け入れ、何もしません。


6

Perl 5の-F46のバイト

#/usr/bin/perl -F
use 5.10.0;
say map{((P,E,T,A)x7)[2..-$^H+($^H=ord)],$_}@F

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


2
P,E,T,A代わりになぜかを尋ねようとしていましたがT,A,P,E、今では2バイトを節約する((P,E,T,A)x7)[2..-$^H+($^H=ord)代わりに使用していることに気付きました((T,A,P,E)x7)[0..-$^H+($^H=ord)-2。いい答えだ!
ケビンCruijssen

本当にいいね!私のナイーブなアプローチよりもはるかに優れています!ただし、リテラル^H\x08)を使用して2バイトを節約できます!
ドムヘイスティングス

@DomHastingsリテラル制御文字変数は、かなり多くのperlバージョンですでに無効になっています。私は古いPerlのバージョンにスコアを主張することができた(ように私は最近のためにやったdo$0)が、私は気にしませんでしたので、それは、ここでの唯一の2バイトだ
トンHospel

ああ、もちろん!これは、macOSのデフォルトが5.18.2であるため、私が最もよく知っているバージョンだからです!
ドムヘイスティングス




4

Python 3、98バイト

lambda a:"".join(sum(zip(a,[("TAPE"*9)[:y>x and~ord(x)+ord(y)]for x,y in zip(a,a[1:])]),()))+a[-1]

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

Asone Tuhidのおかげで-1バイト


@AsoneTuhidありがとう。あなたはかなりオフgolfedきたし、あなたも編集して(禁止されていない)dupesを引き起こすと同じことにTFeldの答えをgolfedので、私はあなた自身の答えを投稿お勧めします
HyperNeutrino

さてさて、持っ-1バイト
Asone Tuhid

@AsoneTuhidああ大丈夫、ありがとう
-HyperNeutrino

4

Scala、66バイト

(s:String)=>s./:("z"){(o,c)=>o+("TAPE"*6).take(c-o.last-1)+c}.tail

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

説明

/: foldLeft over the string
("z") starting with a non-empty string to we don't have to handle the first iteration in a special way
"TAPE"*6 generate a long enough string of TAPETAPETA...
.take(c-o.last-1) take the difference between this character and the previous (now the last char in the output so far) characters from the TAPETAPETA... string. o.last will always be safe because we start with a non-empty string.
o+...+c append it to the output so far ... and add this character to the end
.tail get rid of the leading z we added

PPCGへようこそ。最初の回答はいいですね。私から+1。
ケビンクルーッセン

4

PHP、85バイト

$s=str_split($argv[1]);foreach($s as$l)echo str_pad($l,ord(next($s))-ord($l),'TAPE');

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

説明

$s = str_split($argv[1]);   // convert the parameter string to an array
foreach($s as $l)           // loop the array
echo str_pad(               // print
  $l,                       // the letter
  ord(next($s)) - ord($l),  // calculate the distance to the next letter using ASCII values
  'TAPE'                    // padding string
);                          // profit!

2
サイトへようこそ!:)
DJMcMayhem

3

Javascript、131 127バイト

Rick Hitchcockのおかげで4バイトが節約されました

z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))

展開済み

z = a => [... a] .reduce(
  (x、y)=>
    x + [... Array(
      (f = y.charCodeAt()-(x.slice(-1).charCodeAt()))> 1?(f-1):0
    )]。reduce(
      (e、r、t)=> 
        e + "TAPE" [t%4]、 "")+ y
);

ここでの私の問題は、Javascriptには文字aとbの間の距離を取得するための明確な方法がなかったことです。

<script>
  z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))
</script>

<main>
  <input id="input-box" type="text">
  <pre id=output>output</pre>
</main>

<script>
  inputBox = document.getElementById("input-box");
  inputBox.addEventListener("keyup", function(e){
    output.innerText = z(inputBox.value);
  });
</script>


1
いいね あなたは割り当てることによって、バイト末尾のセミコロンを削除することでバイトを保存し、さらにいくつかを保存することができますcharCodeAt変数に: z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))
リック・ヒッチコック

ありがとう!私はそれがどのように機能するかに絶対にうんざりしていますが、それが将来のために機能することを知っているのは良いことです。
Jhal


2

、20バイト

⭆θ⁺…TAPE∧κ⊖⁻℅ι℅§θ⊖κι

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

 θ              θ       Input string
⭆                       Map over characters
                  κ     Current index
                 ⊖      Decremented
               §        Index into string
             ι          Current character
            ℅ ℅         Ordinal
           ⁻            Subtract
          ⊖             Decremented
         κ              Current index
        ∧               Logical and
    TAPE                Literal string
   …                    Mold to length
                   ι    Current character
  ⁺                     Concatenate
                        Implicitly print

2

ピップ、29バイト

O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa

入力をコマンドライン引数として受け取ります(小文字でも大文字でも構いません)。 オンラインでお試しください!

説明

O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa
                               a is 1st cmdline arg; v is -1 (implicit)
O                              Output without newline
 @a                            the first character of a
                          MPa  Map this function to pairs of successive characters of a:
                    Ag          Get the ASCII codes of the two characters
                  $-            Fold on subtraction (i.e. asc(first)-asc(second))
                v-              -1 minus the above (i.e. asc(second)-asc(first)-1)
              [0      ]         A list containing 0 and the above
            MX                  Max of the list
          @<                    The first ^ characters (with cyclic indexing)
    "TAPE"                      of this string
   {                   }.B      Concatenate the second character

2

JavaScript(ES6)、80 78バイト

f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s

2つの文字間の距離は、それらの連結を基数36に変換し、370、モジュラス37を差し引くことで決定できます。

たとえば、(parseInt('cy',36)-370)%37 == 22

その後padEnd、ギャップを埋めるために使用し、ループを処理するために再帰を使用できます。

テストケース:


2

K4、48バイト

溶液:

{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}

例:

q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"abcmnnnopstzra"
"abcTAPETAPETmnnnopTAstTAPETzra"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aza"
"aTAPETAPETAPETAPETAPETAPEza"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"zyxxccba"
"zyxxccba"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aabbddeeffiiacek"
"aabbTddeeffTAiiaTcTeTAPETk"

説明:

かなり簡単な解決策ですが、バイト数が多い...デルタを見つけ、文字列から取得し"TAPE"、デルタが> 1である元の文字列カットに結合します。

{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"} / the solution
{                                              } / lambda
                                         "TAPE"  / the string TAPE
                                      #\:        / take each-left
           ,[                      ; ]           / join (,)
                                   0             / zero (ie append zero)           
                              "j"$x              / cast input to int
                           -':                   / deltas
                        -1+                      / subtract 1
                      d:                         / assign to d
                    0<                           / delta greater than 0?
                   &                             / indices where true
                 w:                              / assign to w
               d                                 / index into deltas at w
             1_                                  / drop first
         ,'                                      / join each-both
   _[w;x]                                        / cut input x at indices w
 ,/                                              / flatten

2

Excel VBA、106バイト

セルA1を介して大文字の文字列として入力を受け取り、VBEイミディエイトウィンドウに出力する匿名VBEイミディエイトウィンドウ関数。

a=90:For i=1To[Len(A1)]:c=Mid([A1],i,1):b=Asc(c):For j=2To b-a:?Mid("peta",j Mod 4+1,1);:Next:?c;:a=b:Next


2

K(oK)、33バイト

{,/((0|-1+0,1_-':x)#\:"TAPE"),'x}

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

{ } 引数付きの無名関数 x

-':x 各事前を減算(最初の項目の前に虚数0を使用)

1_ 最初のアイテムをドロップ

0, 0を付加します

-1+ -1を追加

0| max(0、...)

(... 左側のリストから各アイテムに)#\:"TAPE"文字列"TAPE"を変形します

(... ),'x対応する文字xを各変形文字列に追加します

,/ すべてを連結する



2

Java(JDK)、91バイト

s->{var p='z';for(var c:s)System.out.print("ETAP".repeat(9).substring(1,c>p?c-p:1)+(p=c));}

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

説明

s->{                       // char[]-accepting lambda consumer, printing a String
 var p='z';                //  store the previous character
 for(var c:s){             //  for each character of the string
  System.out.print(        //   print...
   "ETAP".repeat(9)        //    "ETAP" repeated 9 times (to go above 26 chars)
    .substring(1,          //     of which, we substring c-p -1 characters
     c>p?c-p:1             //
    )                      //
   +(p=c)                  //    and append c, while also storing the previous character
  );

クレジット

  • RMのおかげで-2バイト
  • ceilingcatのおかげで、Java 10+にアップグレードし、タイプをvar
  • -3バイト、Kevin Cruijssenのおかげで、(以前の)代替バージョンの結果を返さずに出力する

int p=1231文字を保存します。それがp最初の文字以上である限り、最初の反復に何があってもかまいません。最初の文字が持つことができる最大値は'z'== ASCII 122なので、123で十分です。また、大文字を使用した場合、123の代わりに91を使用して別の文字を保存できます。
RM

@RM本当にありがとうございます。
オリビエグレゴワール


1

C#(.NET Core)122 111バイト

@KevinCruijssenのおかげで11バイト節約

s=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;)r+="ETAP"[(e-d)%4];return r;}

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

説明:

s => 
{
    var r = "" + s[0];                  //Declare string for the result and initialize with the first character from the input.
    for (                               //Loop over the input,
        int i = 1, e, d;                //starting with the second character, also declare helper variables.
        i < s.Length;                   //Loop until the end of the input is reached.
        r += s[i++])                    //Add the current character to the result and increase the counter.
        for (                           //Loop for adding the TAPE.
            e = d = s[i] - s[i - 1];    //Calculate the differnce between the current and the previous character.
            d-- > 1;)                   //Loop until the difference is 1.
            r += "ETAP"[(e - d) % 4];   //Add a character from the TAPE to the result.
    return r;                           //Return the result.
}

1
いい答え、私からの+1。whileをaに変更してfor角かっこを削除すると、4バイト節約できますfor(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;r+=t[(e-d)%4]);。:)ああ、使用しているのt="ETAP"は1回だけなので、直接使用することができ、さらに7バイト節約stringするvarように変更しますs=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;r+="ETAP"[(e-d)%4]);return r;}
ケビンクルーッセン

@KevinCruijssen:ありがたいことに、forループに移動してブラケットを削除することは考えていませんでした。また、「ETAP」を直接使用できることを逃して愚かだと感じた場合。
raznagul

あなたの答えはまだ素晴らしいので、心配しないでください。:)自分で回答を投稿するたびに、ゴルフのヒントが得られます。また、最初から完全にゴルフをするよりも、既存の回答をさらにゴルフする方が簡単です。PS:あなたはすでにそれを見ているかもしれないが、C#のコード・ゴルフのためのヒントしてゴルフのヒント<すべての言語>は、あなたがまだいない場合通読することも面白いかもしれません。
ケビンクルーッセン



1

Clojure、139 119バイト

#(reduce-kv(fn[r x c](let[a(cycle "TAPE")i int d(-(i(nth(cycle %)(inc x)))(i c))](str r(if(> d 1)(apply str c(take(dec d)a))c))))""(vec %))

文字列を取得し、テープに記録されたものを返す匿名関数。いつものように、Clojureはあまりうまく機能していないようです。私が実際に解決できなかったのは、次の文字を短時間で取得することです。最後の文字ではOutOfBoundsException、明白な理由が得られます。だから私はcycleそれを周りに置きます。もっとエレガントなソリューションがあるかもしれません。

非ゴルフ

#(reduce-kv
  (fn [r x c]
    (let [a (cycle "TAPE")
          i int
          d (-
             (i (nth (cycle %) (inc x)))
             (i c))]
      (str r
           (if (> d 1)
             (apply str c (take (dec d) a))
             c))))
  ""
  (vec %))

更新

数バイトを削り落としました。if違いを減らすことで厄介なステートメントを取り除きました。take数値が0以下の場合は空のリストが生成され、空の文字列が生成されます。

#(reduce-kv(fn[r x c](let[d(-(int(nth(cycle %)(inc x)))(int c)1)](str r c(apply str(take d(cycle "TAPE"))))))""(vec %))

非ゴルフ

#(reduce-kv
  (fn [r x c]
    (let [d (-
             (int (nth (cycle %) (inc x)))
             (int c)
             1)]
      (str
       r
       c
       (apply
        str
        (take
         d
         (cycle "TAPE"))))))
  ""
  (vec %))

1

APL(Dyalog Classic)、30バイト

{∊⍵,¨⍨⍴∘'TAPE'¨0,0⌈-1+2-/⎕a⍳⍵}

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

{ } 引数付きの無名関数

⎕a⍳⍵ アルファベットの文字のインデックスを見つける

2-/ ペアごとの差(前から次へ)

1+ 1を追加

- 否定する

0⌈ max(0、...)

0, 0を付加します

⍴∘'TAPE'¨'TAPE'各文字列を周期的に再形成します

⍵,¨⍨ 引数からの各文字を対応する再形成された文字列に追加します

平らにする


1

CJam27 25バイト

q_:i2ew.{:-~0e>_"TAPE"*<}

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

他のゴルフ言語にはほど遠いですが、とにかくこのゴルフを誇りに思っています。

説明

q                            Read the input
     ew                      And take windows of size
    2                          2
   i                           from the code points
  :                            of each of its characters.
        {               }    For each of these windows:
         :                     Reduce with
          -                      subtraction.
                                 Since there are only 2 elements, this just subtracts them.
             e>                Take the maximum
           ~                     of this difference's bitwise negation
            0                    and zero.
                                 This returns -n-1 if n is negative, and 0 otherwise.
                                 Call this new value m.
                      *        Repeat
                "TAPE"           the string "TAPE" m times.
               _       <       And then take the first m elements.
                             The result of this will be an array of strings which consist of
                             the string "TAPE" repeated the proper amount of times.
       .                     Zip this array with the original input.
                             Since the original input is one element longer than this array,
                             the nothing is pushed after the final character.
                             Implicitly print everything.



0

Javaの、213の 166 153バイト

i->{String o="";for(int a=0,l=i.length;++a<=l;){char u=i[a-1],n;o+=u;if(a<l){n=i[a];o+="TAPETAPETAPETAPETAPETAPET".substring(0,n-u>0?n+~u:0);}}return o;}

オンラインで試す

    String o = "";
    for (int a = 0, l = i.length; ++a <= l; ) {              // for each character
        char u = i[a - 1];                                    //  current character
        o += u;                                               //  add current character to output string 
        if (a < l) {                                          //  if it's not the last one
            char n = i[a];                                    //  next character
            o += "TAPETAPETAPETAPETAPETAPET".substring(0, n - u > 0 ? n +~ u : 0); // fill with enough tape but only forward
        }
    }
    return o;

改善してください。

空白に関するヒントを提供してくれた@cairdcoinheringaahingに感謝します。テープストリングに関するヒントを提供してくれた@RMに感謝します。ラムダと式のヒントを提供してくれた@KevinCruijssenに感謝します。


1
サイトへようこそ!あなたはこの答えをゴルフするために多くの空白を削除し、Javaでゴルフをするためのこれらのヒントを必ず確認してください!
コイナーリンガーを育てる

1
変数tを使用するのは一度だけなので、変数tを作成する必要はありません。あなただけができます"TAPETAPETAPETAPETAPETAPET".substring...
RM

PPCGへようこそ!もののほか@RMは言った、あなたはゴルフいくつかのより多くの事ができます。int a=1,l=i.length;a<=l;a++することができint a=0,l=i.length;++a<=l;char u=i[a-1];o+=u;if(a<l){char n=することができchar u=i[a-1],n;o+=u;if(a<l){n=(n-u)括弧を必要としない、とn-u-1することができn+~u。また、あなたの答えは現在、関数ではなくスニペットです。ラムダにするためにi->{は、前と}最後に追加する必要があります。合計で:オンラインで試してみてください。153バイト
ケビンクルーイッセン

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