28
\$\begingroup\$

Given a non-empty string of lowercase ASCII letters a-z, output that string with each consecutive “run” of the same letter lengthened by one more copy of that letter.

For example, dddogg (3 d’s, 1 o, 2 g’s) turns into ddddooggg (4 d’s, 2 o’s, 3 g’s).

This is : the shortest answer in bytes wins.

Test cases

aabbcccc -> aaabbbccccc
doorbell -> ddooorrbbeelll
uuuuuuuuuz -> uuuuuuuuuuzz
q -> qq
xyxyxy -> xxyyxxyyxxyy
xxxyyy -> xxxxyyyy
\$\endgroup\$
  • \$\begingroup\$ Related (only add another character if the length of the run is odd) \$\endgroup\$ – MildlyMilquetoast May 8 '17 at 17:23

36 Answers 36

11
\$\begingroup\$

05AB1E, 5 bytes

.¡€ĆJ

Explanation:

Example input: "dddogg"
.¡       Split into chunks of consecutive equal elements
         stack: [['ddd', 'o', 'gg']]
  €      For each...
   Ć       Enclose; append the first character to the end of the string
         stack: [['dddd', 'oo', 'ggg']]
    J    Join array elements into one string
         stack: ['ddddooggg']
Implicitly output top element in stack: "ddddooggg"

Try it online or as a test suite.

Enclose is a pretty new builtin; it's the first time I've used it. Very convenient ;)

05AB1E, 4 bytes (non-competing)

γ€ĆJ

has been replaced by γ in the latest update.

\$\endgroup\$
  • \$\begingroup\$ Enclose is one of the craziest builtins ever. \$\endgroup\$ – Erik the Outgolfer May 6 '17 at 17:41
  • 3
    \$\begingroup\$ @EriktheOutgolfer Crazy? Nah. \$\endgroup\$ – Okx May 6 '17 at 17:41
  • \$\begingroup\$ I think you mean dddd for the first element of the array on the stack in the explanation after "enclose" is executed. \$\endgroup\$ – Esolanging Fruit May 7 '17 at 11:43
  • \$\begingroup\$ Woah, wait a minute, what the hell is Ć? \$\endgroup\$ – Magic Octopus Urn May 8 '17 at 15:12
  • \$\begingroup\$ Also, xx -> xxxx when it should be xx -> xxx...? \$\endgroup\$ – Magic Octopus Urn May 8 '17 at 15:13
15
\$\begingroup\$

Python 3, 44 bytes

for c in input():print(c,end=c[id==c:]);id=c

Try it online!

\$\endgroup\$
10
\$\begingroup\$

Retina, 11 bytes

(.)\1*
$1$&

Try it online!

Replaces each run of characters with one of the run's characters followed by the run itself.

\$\endgroup\$
8
\$\begingroup\$

Pyth, 7 bytes

r9hMMr8

Test suite.

How it works

r9hMMr8  example input: "xxyx"
     r8  run-length encoding
         [[2, "x"], [1, "y"], [1, "x"]]
  hMM    apply h to each item
         this takes advantage of the overloading
         of h, which adds 1 to numbers and
         takes the first element of arrays;
         since string is array of characters in
         Python, h is invariant on them
         [[3, "x"], [2, "y"], [2, "x"]]
r9       run-length decoding
         xxxyyxx
\$\endgroup\$
7
\$\begingroup\$

MATL, 5 bytes

Y'QY"

Try it online!

Explanation

Consider input 'doorbell'.

Y'    % Implicit input. Run-length encoding
      % STACK: 'dorbel', [1 2 1 1 1 2]
Q     % Increase by 1, element-wise
      % STACK: 'dorbel', [2 3 2 2 2 3]
Y"    % Run-length decoding. Implicit display
      % STACK: 'ddooorrbbeelll'
\$\endgroup\$
6
\$\begingroup\$

Alice, 17 bytes

/kf.>o./
@i$QowD\

Try it online!

Explanation

/.../
@...\

This is a framework for programs which operate entirely in Ordinal mode and are essentially linear (simple loops can be written, and one is used in this program, but it's trickier to work with otherwise branching control flow here). The instruction pointer bounces diagonally up and down through the code from left to right, then gets shifted by one cell by the two mirrors at the end, and the moves back from right to left, executing the cells it skipped on the first iteration. The linearised form (ignoring the mirrors) then basically looks like this:

ifQ>w.Doo.$k@

Let's go through this:

i     Read all input as a string and push it to the stack.
f     Split the string into runs of equal characters and push those
      onto the stack.
Q     Reverse the stack, so that the first run is on top.
>     Ensure that the horizontal component of the IP's movement is east.
      This doesn't do anything now, but we'll need it after each loop
      iteration.
w     Push the current IP address to the return address stack. This marks
      the beginning of the main loop.

  .     Duplicate the current run.
  D     Deduplicate the characters in that run so we just get the character
        the run is made up of.
  o     Output the character.
  o     Output the run.
  .     Duplicate the next run. When we've processed all runs, this will
        duplicate an implicit empty string at the bottom of the stack instead.
  $     If the string is non-empty (i.e. there's another run to process),
        execute the next command otherwise skip it.

k     Pop an address from the return address stack and jump there. Note that
      the return address stack stores no information about the IP's direction,
      so after this, the IP will move northwest from the w. That's the wrong
      direction though, but the > sets the horizontal component of the IP's
      direction to east now, so that the IP passes over the w again and can
      now execute the next iteration in the correct direction.
@     Terminate the program.
\$\endgroup\$
5
\$\begingroup\$

Jelly, 6 bytes

Œg;Q$€

Try it online!

Only works as a full program (i.e. stringified output).

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

Brachylog, 8 bytes

ḅ{t,?}ᵐc

Try it online!

Explanation

             Example input: "doorbell"
ḅ            Blocks: ["d","oo","r","b","e","ll"]
 {   }ᵐ      Map: ["dd","ooo","rr","bb","ee","lll"]
  t            Tail: "d" | "o" | "r" | "b" | "e" | "l"
   ,?          Prepend to input: "dd" | "ooo" | "rr" | "bb" | "ee" | "lll"
       c     Concatenate: "ddooorrbbeelll"
\$\endgroup\$
  • \$\begingroup\$ 2/10 not declarative enough \$\endgroup\$ – Leaky Nun May 6 '17 at 17:37
  • \$\begingroup\$ @LeakyNun I actually found that one too just after posting this one \$\endgroup\$ – Fatalize May 6 '17 at 17:37
  • \$\begingroup\$ You really need to make ~ take precedence over metapredicates (or change it to a postfix operation); if you did, you could do this in seven. \$\endgroup\$ – user62131 May 6 '17 at 18:35
4
\$\begingroup\$

C, 49 bytes

i;f(char*s){for(;putchar(*s);)i=s[i]^s[1]||!s++;}

See it work online.

\$\endgroup\$
3
\$\begingroup\$

Python 2, 47 bytes

f=lambda s:s and-~(s[0]*2!=s[:2])*s[0]+f(s[1:])

Try it online!

\$\endgroup\$
3
\$\begingroup\$

C, 53 bytes

i;f(char*s){for(;i=*s++;)putchar(i^*s?putchar(i):i);}

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Thank you for posting this solution as it motivated me to come up with a shorter solution that omits the second putchar. Upvoted. \$\endgroup\$ – 2501 May 7 '17 at 9:13
3
\$\begingroup\$

PHP, 40 Bytes

<?=preg_filter('#(.)\1*#',"$1$0",$argn);

Online Version

PHP<7.1, 44 Bytes

Version without Regex

for(;a&$c=$argn[$i++];)echo$c[$c==$l].$l=$c;

Online Version

\$\endgroup\$
3
\$\begingroup\$

Japt, 8 bytes

7 bytes of code, +1 for the -P flag.

ó¥ ®+Zg

Test it online!

Explanation

This uses the ó (partition on falsy) built-in that I just added yesterday:

ó¥  ®   +Zg
ó== mZ{Z+Zg}

ó==           // Split the input into runs of equal chars.
    mZ{    }  // Replace each item Z in this array with
       Z+Zg   //   Z, concatenated with the first char of Z.
-P            // Join the resulting array back into a string.
              // Implicit: output result of last expression
\$\endgroup\$
3
\$\begingroup\$

Hexagony, 33 bytes

\~..,}/',\<.-/.<@;$>.${;/${/"$.>$

Expanded:

   \ ~ . .
  , } / ' ,
 \ < . - / .
< @ ; $ > . $
 { ; / $ { /
  " $ . > $
   . . . .

Try it online!

The pseudo-code is more or less:

char = readchar()
while (char > 0)
    print(char)
    run_char = char
    do
        print(char)
        char = readchar()
    while (run_char == char)
\$\endgroup\$
3
\$\begingroup\$

JavaScript (ES6), 33 30 bytes

s=>s.replace(/(.)\1*/g,"$1$&")

Try It

f=
s=>s.replace(/(.)\1*/g,"$1$&")
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("aabbcccc")) // aaabbbccccc
console.log(f("doorbell")) // ddooorrbbeelll
console.log(f("uuuuuuuuuz")) // uuuuuuuuuuzz
console.log(f("q")) // qq
console.log(f("xyxyxy")) // xxyyxxyyxxyy
console.log(f("xxxyyy")) // xxxxyyyy
<input id=i><pre id=o>

\$\endgroup\$
3
\$\begingroup\$

brainfuck, 23 bytes

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

Try it online!

Explanation

,            read the first input character
 [           main loop to be run for each input character
 .           output the character once
 [->->+<<]   subtract from previous character (initially 0), and create a copy of this character
 >[          if different from previous character:
   [-]       zero out cell used for difference (so this doesn't loop)
   >.<       output character again from copy
 ]
 ,           read another input character
]
\$\endgroup\$
  • 1
    \$\begingroup\$ Will this work with letter runs > 256? \$\endgroup\$ – Esolanging Fruit May 9 '17 at 2:24
  • \$\begingroup\$ @Challenger5 Yes. The run length isn't even tracked, so there is no way for run length to overflow. \$\endgroup\$ – Nitrodon May 9 '17 at 2:56
2
\$\begingroup\$

Perl 6, 18 bytes

{S:g/)>(.)$0*/$0/}

Try it

Expanded:

{   # bare block lambda with implicit parameter 「$_」

  S        # replace and return
  :global  # all occurrences
  /

    )>     # don't actually remove anything after this

    (.)    # match a character

    $0*    # followed by any number of the same character

  /$0/     # replace with the character (before the match)
}
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 8 bytes

.¡DÔ‚ø˜J

Try it online!

Explanation:

.¡DÔ‚ø˜J
.¡       Split equal runs of input
  D      Duplicate
   Ô     Take connected-uniquified
    ‚    Pair connected-uniquified equal runs with original equal runs
     ø   Zip
      ˜  Deep-flatten (i.e. normal flattening)
       J Join elements together
\$\endgroup\$
2
\$\begingroup\$

Haskell, 36 bytes

f(a:b:c)=a:[a|a/=b]++f(b:c)
f x=x++x

Usage example: f "aab" -> "aaabb". Try it online!

When the string has at least two chars, bind a to the first char, b to he second and c to the rest of the string. The output is a followed by a if a is not equal to b followed by a recursive call with b:c. If there's only one char, the result is two times this char.

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

CJam, 10 bytes

le`1af.+e~

Try it online!

Explanation:

e# Input: doorbell
l   e# Read line:              | "doorbell"
e`  e# Run-length encode:      | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]]
1a  e# Push [1]:               | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]] [1]
f.+ e# Vectorized add to each: | [[2 'd] [3 'o] [2 'r] [2 'b] [2 'e] [3 'l]]
e~  e# Run-length decode:      | "ddooorrbbeelll"
e# Implicit output: ddooorrbbeelll
\$\endgroup\$
2
\$\begingroup\$

Ruby, 30 bytes

->s{s.gsub(/((.)\2*)/){$1+$2}}
\$\endgroup\$
2
\$\begingroup\$

Jelly, 5 bytes

n2\׿

Try it online!

How it works

n2\׿  Main link. Argument: s (string)

n2\    Reduce all overlapping slices of length two by non-equal.
       For input "doorbell", this returns [1, 0, 1, 1, 1, 1, 0].
   ×   Multiply the characters of s by the Booleans in the resulting array. This is
       essentially a bug, but integer-by-string multiplication works as in Python.
       For input "doorbell", this returns ['d', '', 'o', 'r', 'b', 'e', '', 'l'].
       Note that the last character is always left unchanged, as the Boolean array
       has one fewer element than s.
    ż  Zip the result with s, yielding an array of pairs.
       For input "doorbell", this returns [['d', 'd'], [[], 'o'], ['o', 'o'],
           ['r', 'r'], ['b', 'b'], ['e', 'e'], [[], 'l'], ['l', 'l']].
       (implicit) Print the flattened result.
\$\endgroup\$
  • \$\begingroup\$ Well played, Dennis. \$\endgroup\$ – Leaky Nun May 7 '17 at 2:54
1
\$\begingroup\$

Batch, 140 bytes

@set/ps=
@set r=
:g
@if not "%s:~,1%"=="%s:~1,1%" set r=%r%%s:~,1%
@set r=%r%%s:~,1%
@set s=%s:~1%
@if not "%s%"=="" goto g
@echo %r%

Takes input on STDIN.

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

sed, 18 15 bytes (+1 for -r)

s/(.)\1*/\1&/g

Original solution

s/((.)\2*)/\1\2/g
\$\endgroup\$
1
\$\begingroup\$

R, 36 bytes

gsub("((.)\\1*)","\\2\\1",scan(,""))
\$\endgroup\$
1
\$\begingroup\$

PowerShell, 50 bytes

{-join([char[]]$_|%{if($_-ne$p){($p=$_)}$_});rv p}

Try it online!

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

Mathematica, 34 21 bytes

Thanks to Martin Ender for finding the right way to do this in Mathematica, saving 13 bytes!

##&[#,##]&@@@Split@#&

Pure function using an array of characters as both input and output formats. Split separates a list into its runs of equal characters. ##&[#,##]& is a function that returns a sequence of arguments: the first argument it's fed, then all of the arguments (so repeating the first one in particular); this is applied (@@@) to every sublist of the Split list.

\$\endgroup\$
  • 1
    \$\begingroup\$ Maybe ##&[#,##]&@@@Split@#&? (Untested.) \$\endgroup\$ – Martin Ender May 6 '17 at 17:20
  • 1
    \$\begingroup\$ ^ Now tested. Btw, Gather doesn't actually work if there are multiple runs of the same character (but luckily Split is a byte shorter anyway) \$\endgroup\$ – Martin Ender May 6 '17 at 17:53
  • \$\begingroup\$ (oh yeah, I meant Split in my heart) Wonderful construction in your first comment! \$\endgroup\$ – Greg Martin May 8 '17 at 5:17
1
\$\begingroup\$

Java, 151 146 60 bytes

String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
  • -5 bytes, thanks to @FryAmTheEggman
  • -86 bytes, thanks to @KevinCruijssen

Regex

(         )     group

 (.)            a character

     \\2*       optional repetition

Detailed

import java.util.*;
import java.lang.*;
import java.io.*;

class H
{
    public static String f(String s)
    {
        return s.replaceAll("((.)\\2*)","$1$2");
    }

    public static void main(String[] args)
    {
        f("dddogg");
    }
}
\$\endgroup\$
  • \$\begingroup\$ Hadn't noticed there was already a Java answer, so I've deleted mine. But why the Matcher and Pattern? You can golf it to 60 bytes like this: String f(String s){return s.replaceAll("((.)\\2*)","$1$2");} \$\endgroup\$ – Kevin Cruijssen May 8 '17 at 11:35
  • \$\begingroup\$ @KevinCruijssen fixed now, thx. \$\endgroup\$ – Khaled.K May 8 '17 at 14:17
1
\$\begingroup\$

brainfuck, 38 bytes

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

Try it online!

,.               print the "doubling" of the first char of input
[                this main loop runs on every char
  .              print it "normally" (the not-doubling)
  >,             read the next char
  [              judiciously placed "loop" to prevent printing NULs
    [->+>+<<]    copy new char at position p to p+1 and p+2
    <[->>-<<]>>  subtract old char from p+1 - zero if same, nonzero otherwise
    [            if it *is* different (nonzero)...
      [-]        clear it
      >.<        print the char (at p+2 now) again
    ]
  ]
  >              the new char is now the old char
]
\$\endgroup\$
1
\$\begingroup\$

Alice, 12 bytes

Two bytes were golfed thanks to Martin Ender even before this answer was posted. He's more powerful than you could ever imagine.

I4&.h%?-$OO!

Try it online!

Explanation

I                 Input a character and push its unicode value
 4&.              Push 4 more copies of this value to the stack
                  (they will be needed for the following operations)
    h%            Try to compute n%(n+1), exits with an error if n==-1
                  which happens on EOF
      ?           Push a copy of what's currently on the tape.
                  In the first iteration this will push -1, in following
                  iterations it will push the previous character.
       -$O        If the two topmost values on the stack are different
                  output the third one. This will output one more copy of
                  any new character encountered.
          O       Output this character.
           !      Store this character on the tape.

                  Execution loops back to the beginning of the line.
\$\endgroup\$

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.