40
\$\begingroup\$

Challenge:

Given a string only containing upper- and/or lowercase letters (whichever you prefer), put tape horizontally to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going forward), and filling the space with as much TAPE/tape as we would need.


Example:

Input: abcmnnnopstzra
Output: abcTAPETAPETmnnnopTAstTAPETzra

Why?

  • Between c and m should be defghijkl (length 9), so we fill this with TAPETAPET;
  • Between p and s should be qr (length 2), so we fill this with TA;
  • Between t and z should be uvwxy (length 5), so we fill this with TAPET.

Challenge rules:

  • The difference only applies forward, so no tape between zra.
  • It is possible to have multiple of the same adjacent letters like nnn.
  • You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
  • You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and TAPE.
  • It is possible no TAPE is necessary, in which case the input remains unchanged.

General rules:

  • This is , so the shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link to a test for your code.
  • Also, please add an explanation if necessary.

Test cases:

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"
\$\endgroup\$
  • 10
    \$\begingroup\$ Unsure why we would discard some between fix-ups (e.g. we discard APE after fixing with TAPETAPET and before fixing with TA) seems like a waste of good TAPE to me, but maybe that's just how I roll (sorry). \$\endgroup\$ – Jonathan Allan Mar 5 '18 at 15:37
  • \$\begingroup\$ @JonathanAllan Hehe, you're indeed right that it's kinda a waste of 'tape'. Hmm, could be something I might use in part 2 of the challenge. ;) \$\endgroup\$ – Kevin Cruijssen Mar 5 '18 at 15:48
  • \$\begingroup\$ What about if the string comes in with tape - e.g., abTAPEgh ? \$\endgroup\$ – manassehkatz Mar 5 '18 at 15:50
  • \$\begingroup\$ @manassehkatz It would be interpret as every other character, so ab[TAPETAPETAPETAPET]TA[TAPETAPETAPETA]PE[T]gh (added the [] to make it more readable). \$\endgroup\$ – Kevin Cruijssen Mar 5 '18 at 15:57
  • 1
    \$\begingroup\$ @KevinCruijssen Which is consistent, though (as with the "wasting tape" question) not 100% logical. So maybe one more test case: Input TAPE, output TATAPETAPETAPETAPE (I think I got that right...) \$\endgroup\$ – manassehkatz Mar 5 '18 at 16:05

30 Answers 30

8
\$\begingroup\$

05AB1E, 14 12 bytes

'¡ÉIÇ¥<∍‚ζJJ

Try it online!

Explanation

'¡É            # 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
\$\endgroup\$
  • 4
    \$\begingroup\$ Would you mind adding an explanation? I think it's fairly similar to the Jelly answer, but I'm curious which of the characters are used for which of the operations to get the result. One of the general rules in my challenges: "Also, please add an explanation if necessary.", with languages like Jelly, 05AB1E, Charcoal, APL, etc. it's save to assume most people can't read it and an explanation is mandatory. :) \$\endgroup\$ – Kevin Cruijssen Mar 5 '18 at 14:14
  • \$\begingroup\$ @KevinCruijssen: Certainly. I usually add an explanation to my 05AB1E answers, but I don't always have time right when I post it. \$\endgroup\$ – Emigna Mar 5 '18 at 14:31
  • 1
    \$\begingroup\$ @KevinCruijssen in the arguments of any 05AB1E TIO link you can add -d to get the raw stack operation-by-operation dump of what is going on in lieu of an explanation, but I try to post them too it isn't straightforward especially on some of mine LOL. \$\endgroup\$ – Magic Octopus Urn Mar 5 '18 at 20:34
10
\$\begingroup\$

Jelly, 13 bytes

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

Try it online!

Explanation

OI’“¡ʂƁ»ṁ$€ż@ – Full program. Take a string as a command line argument.
O             – Ordinal. Get the ASCII values of each character.
 I’           – Get the increments (deltas), and subtract 1 from each.
          €   – For each difference I...
   “¡ʂƁ»ṁ$    – Mold the compressed string "tape" according to these values.
                Basically extends / shortens "tape" to the necessary length.
           ż@ – Interleave with the input.
\$\endgroup\$
  • \$\begingroup\$ Here's a trick to get you down to 12 \$\endgroup\$ – Jonathan Allan Mar 5 '18 at 13:46
  • \$\begingroup\$ @JonathanAllan That seems invalid to me. It outputs abctapetapetmnnnopapstetapezra instead of abctapetapetmnnnoptasttapetzra. \$\endgroup\$ – Mr. Xcoder Mar 5 '18 at 13:51
  • 7
    \$\begingroup\$ Oh, yes it's invalid - I had not realised we were to waste tape from the roll! \$\endgroup\$ – Jonathan Allan Mar 5 '18 at 13:54
7
\$\begingroup\$

Haskell, 58 bytes

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

Try it online! The function f recurses over the string and looks at consecutive characters x and y. cycle"TAPE" yields the infinite string "TAPETAPETAPE...". [x..y] gets the range of characters from x to y inclusive, so we need to subtract two from the length. In case x occurs later in the alphabet then y or both are the same character, we get a negative number after subtracting, but luckily take accepts those as well and just takes nothing.

\$\endgroup\$
6
\$\begingroup\$

Perl 5, -F 46 bytes

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

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ Was about to ask why P,E,T,A instead of T,A,P,E, but I now notice you've used ((P,E,T,A)x7)[2..-$^H+($^H=ord) instead of ((T,A,P,E)x7)[0..-$^H+($^H=ord)-2 to save two bytes. Nice answer! \$\endgroup\$ – Kevin Cruijssen Mar 5 '18 at 11:53
  • \$\begingroup\$ Very nice indeed! Much better than my naiive approach! You can save 2 bytes using literal ^H (\x08) though! \$\endgroup\$ – Dom Hastings Mar 5 '18 at 14:17
  • \$\begingroup\$ @DomHastings Literal control character variables have been disabled for quite many perl versions already. I could claim a score on an older perl version (Like I did recently for do$0) but it's only 2 bytes here, so I didn't bother \$\endgroup\$ – Ton Hospel Mar 5 '18 at 14:36
  • \$\begingroup\$ Ah, of course! It's because macOS has 5.18.2 by default, so it's the version I'm most familiar with! \$\endgroup\$ – Dom Hastings Mar 5 '18 at 16:52
5
\$\begingroup\$

Python 2, 96 87 80 bytes

lambda s:''.join(c+(C>c)*('TAPE'*6)[:ord(C)+~ord(c)]for c,C in zip(s,s[1:]+' '))

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Haskell, 64 bytes

t="TAPE"++t
e=fromEnum
f(x:y:z)=x:take(e y-e x-1)t++f(y:z)
f x=x

Handles strings of either uppercase or lowercase letters, but not both.

Try it online!

\$\endgroup\$
4
\$\begingroup\$

C, 84 bytes

i,l;f(char*s){for(;*s;)for(putchar(l=*s++),l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}

Try it online!

C (run on Windows Command Prompt), 81 bytes

i,l;f(char*s){for(;putchar(l=*s++);)for(l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}

Output:

\$\endgroup\$
4
\$\begingroup\$

Python 3, 98 bytes

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]

Try it online!

-1 byte thanks to Asone Tuhid

\$\endgroup\$
  • \$\begingroup\$ @AsoneTuhid Thanks. I'd recommend posting your own answer because you've golfed off quite a bit and you also golfed TFeld's answer to the same thing so editing would cause dupes (which isn't disallowed) \$\endgroup\$ – HyperNeutrino Mar 5 '18 at 16:58
  • \$\begingroup\$ Alright, have a -1 byte \$\endgroup\$ – Asone Tuhid Mar 5 '18 at 17:21
  • \$\begingroup\$ @AsoneTuhid oh okay, thanks \$\endgroup\$ – HyperNeutrino Mar 5 '18 at 18:41
4
\$\begingroup\$

Scala, 66 bytes

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

Try it online!

Explanation

/: 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
\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG, and nice first answer! +1 from me. \$\endgroup\$ – Kevin Cruijssen Mar 6 '18 at 11:50
4
\$\begingroup\$

PHP, 85 bytes

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

Try it online!

Explanation

$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!
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to the site! :) \$\endgroup\$ – DJMcMayhem Mar 7 '18 at 23:29
3
\$\begingroup\$

Javascript, 131 127 Bytes

4 Bytes saved thanks to Rick Hitchcock.

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

Unrolled

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

My Problem here is that Javascript had no clean way to get the distance between character a and 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>

\$\endgroup\$
  • 1
    \$\begingroup\$ Nice. You can save a byte by removing the trailing semi-colon, and save a few more bytes by assigning charCodeAt to a variable: 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)) \$\endgroup\$ – Rick Hitchcock Mar 5 '18 at 22:26
  • \$\begingroup\$ Thanks! I'm absolutely disgusted by how that works, but it's good to know that it does for the future. \$\endgroup\$ – Jhal Mar 6 '18 at 8:57
3
\$\begingroup\$

Python 2 / 3, 70 69 bytes

f=lambda s,*t:t and s+('TAPE'*6)[:max(ord(t[0])+~ord(s),0)]+f(*t)or s

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 20 bytes

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

Try it online! Explanation:

 θ              θ       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
\$\endgroup\$
2
\$\begingroup\$

Pip, 29 bytes

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

Takes input as a command-line argument (lower- or uppercase, doesn't matter). Try it online!

Explanation

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
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 80 78 bytes

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

The distance between two characters can be determined by converting their concatenation to base 36, subtracting 370, modulus 37.

For example, (parseInt('cy',36)-370)%37 == 22.

We can then use padEnd to fill in the gaps, and recursion to handle the loop.

Test Cases:

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

console.log(f('abcmnnnopstzra'));
console.log(f('aza'));
console.log(f('ghijk'));
console.log(f('aabbddeeffiiacek'));
console.log(f('zyxxccba'));
console.log(f('abccxxyz'));
console.log(f('abtapegh'));
console.log(f('tape'));

\$\endgroup\$
2
\$\begingroup\$

K4, 48 bytes

Solution:

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

Examples:

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"

Explanation:

Fairly simple solution, but a high byte count... Find the deltas, take from the string "TAPE", join to the original string cut where the deltas are > 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
\$\endgroup\$
2
\$\begingroup\$

Excel VBA, 106 bytes

An anonymous VBE immediate window function that takes input as an uppercase string via cell A1 and outputs to the VBE immediate window.

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
\$\endgroup\$
2
\$\begingroup\$

Ruby, 59 53 bytes

->s{s.reduce{|x,y|x+y.rjust(y.ord-x[-1].ord,"TAPE")}}

Try it online!

This is actually pretty straightforward - we take input as split our string into an array of chars (thanks to Asone Tuhid for pointing this out) and apply reduce operation, where we justify each char to the required length using "TAPE" as filler string.

\$\endgroup\$
  • \$\begingroup\$ The question says you can take input as an array of characters. (53 bytes) \$\endgroup\$ – Asone Tuhid Mar 7 '18 at 16:08
2
\$\begingroup\$

K (oK), 33 bytes

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

Try it online!

{ } anonymous function with argument x

-':x subtract each prior (use an imaginary 0 before the first item)

1_ drop first item

0, prepend a 0

-1+ add -1

0| max(0, ...)

(...)#\:"TAPE" reshape the string "TAPE" to each item from the list on the left

(...),'x append the corresponding character from x to each reshaped string

,/ concatenate all

\$\endgroup\$
2
\$\begingroup\$

Java (OpenJDK 9), 100 bytes

s->{int p=99,i;String r="";for(char c:s){for(i=0;++i<c-p;)r+="ETAP".charAt(i%4);r+=c;p=c;}return r;}

Try it online!

Requires input in uppercase.

Explanation

s->{                       // char[]-accepting lambda function, outputting a String
 int p=99,                 //  store the previous character
     i;                    //  counter
 String r="";              //  result-string
 for(char c:s){            //  for each character of the string
  for(i=0;++i<c-p;)        //   for each letter of difference between the previous character and the current one
   r+="ETAP".charAt(i%4);  //    append "TAPE"-letters
  r+=c;                    //   append the end-letter to the result String
  p=c;                     //   update previous-character to the current one
 }                         //  end-loop
 return r;                 //  return the result-string
}                          // end lambda function

Credits

  • -2 bytes thanks to R.M
\$\endgroup\$
  • \$\begingroup\$ int p=123 would save one character. It doesn't matter what p is in the first iteration, as long as it is larger than or equal to the first character. The largest value the first character can have is 'z' == ASCII 122, so 123 is good enough. Also, if you used capital letters, you could use 91 instead of 123, saving another character. \$\endgroup\$ – R.M Mar 11 '18 at 17:45
  • \$\begingroup\$ @R.M Thanks, indeed that works! \$\endgroup\$ – Olivier Grégoire Mar 11 '18 at 19:26
2
\$\begingroup\$

Ruby, 78 77 64 62 bytes

-1 byte thanks to Kevin Cruijssen

f=->s,*t{t[0]?s+('TAPE'*6)[0,[0,t[0].ord+~s.ord].max]+f[*t]:s}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You can save a byte changing ord-l[-1].ord-1 to ord+~l[-1].ord. Nice answer, though. +1 from me. \$\endgroup\$ – Kevin Cruijssen Mar 5 '18 at 15:22
1
\$\begingroup\$

C# (.NET Core), 122 111 bytes

Saved 11 bytes thanks to @KevinCruijssen

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;}

Try it online!

Explanation:

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.
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Nice answer, +1 from me. You can save 4 bytes by changing the while to a for and removing the brackets: 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]);. :) Oh, and since you're using t="ETAP" only once, you can use it directly, and change string to var to save 7 more bytes: 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;}. \$\endgroup\$ – Kevin Cruijssen Mar 6 '18 at 13:21
  • \$\begingroup\$ @KevinCruijssen: Thanks, I wouldn't have thought about getting rid of the brackets by moving the stuff to the for loop. Also if feel stupid for missing that I can use "ETAP" directly. \$\endgroup\$ – raznagul Mar 6 '18 at 13:29
  • \$\begingroup\$ Your answer is still great, so don't worry about it. :) I get golf-tips almost every time I post an answer myself.. And it's also easier to golf an existing answer further than having it completely golfed right from the start. PS: you might have already seen them, but Tips for code-golfing in C# and Tips for golfing in <all languages> might be interesting to read through if you haven't yet. \$\endgroup\$ – Kevin Cruijssen Mar 6 '18 at 13:39
1
\$\begingroup\$

Yabasic, 119 bytes

An anonymous function that takes input as an uppercase string and outputs to STDOUT.

Input""s$
a=90
For i=1To Len(s$)
c$=Mid$(s$,i,1)
b=Asc(c$)
For j=2To b-a
?Mid$("peta",Mod(j,4)+1,1);
Next
?c$;
a=b
Next

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Python 3, 90 bytes

p,o=' ',''
for t in input():y=(ord(t)-ord(p)-1)*(p!=' ');o+=('TAPE'*y)[0:y]+t;p=t
print(o)

Try it Online

\$\endgroup\$
  • \$\begingroup\$ Hi, I've fixed your title from **title** to #title. Also, would you mind adding a TryItOnline-link with test code? \$\endgroup\$ – Kevin Cruijssen Mar 7 '18 at 9:03
1
\$\begingroup\$

Clojure, 139 119 bytes

#(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 %))

Anonymous function which take the string and returns the taped one. As always, Clojure doesn't seem to perform all too well. What I couldn't really work out is fetching the next char in a short way. On the last char I would get an OutOfBoundsException, reason obvious. So I put a cycle around it. Maybe there is a more elegant solution.

Ungolfed

#(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 %))

Update

Managed to shafe off a few bytes. Got rid of the pesky if statement by decrementing the difference. take produces an empty list if the number is 0 or less which in turn results in an empty string.

#(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 %))

Ungolfed

#(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 %))
\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog Classic), 30 bytes

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

Try it online!

{ } anonymous function with argument

⎕a⍳⍵ find indices of its chars in the alphabet

2-/ pairwise differences (prev minus next)

1+ add 1

- negate

0⌈ max(0, ...)

0, prepend a 0

⍴∘'TAPE'¨ reshape cyclically the string 'TAPE' to each

⍵,¨⍨ append each char from the argument to the corresponding reshaped string

flatten

\$\endgroup\$
1
\$\begingroup\$

CJam, 27 25 bytes

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

Try it online!

Far, far from the other golfing languages, but I'm proud of this golf anyway.

Explanation

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.
\$\endgroup\$
1
\$\begingroup\$

Husk, 26 25 bytes

ΣSoż+C1(moo↑¢¨tȦ9¨>0←Ẋ-mc

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PowerShell, 72 bytes

-join($args|% t*y|%{for(;$p*(++$p-lt$_)){'TAPE'[$i++%4]}$i=0;$p=+$_;$_})

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Java , 213 166 153 bytes

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;}

try it online

    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;

Please help me make it better.

Thanks to @cairdcoinheringaahing for the tip on whitespaces. Thanks to @R.M for the tip on tape string. Thanks to @KevinCruijssen for the lambda and expressions tips.

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to the site! You can remove a lot of whitespace to golf this answer and make sure to check these tips for golfing in Java! \$\endgroup\$ – caird coinheringaahing Mar 7 '18 at 16:12
  • 1
    \$\begingroup\$ You don't need to create the variable t, because you're only using it once. You can just do "TAPETAPETAPETAPETAPETAPET".substring.... \$\endgroup\$ – R.M Mar 11 '18 at 17:53
  • \$\begingroup\$ Welcome to PPCG! In addition to what @R.M said, you can golf a few more things: int a=1,l=i.length;a<=l;a++ can be int a=0,l=i.length;++a<=l;, char u=i[a-1];o+=u;if(a<l){char n= can be char u=i[a-1],n;o+=u;if(a<l){n=, (n-u) doesn't need the parenthesis, and n-u-1 can be n+~u. Also, your answer is currently a snippet instead of a function. To make it a lambda you'll need to add i->{ in front and } at the end. So in total: Try it online. 153 bytes \$\endgroup\$ – Kevin Cruijssen Mar 12 '18 at 8:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.