g | x | w | all
Bytes Lang Time Link
034Julia 1.0240625T125352Zint 21h
009Vyxal230810T203535ZJoao-3
030Arturo230810T174546Zchunes
003Thunno 2 J230810T154946ZThe Thon
051Prolog SWI220904T193726ZnaffetS
003Vyxal d220904T193423ZnaffetS
00505AB1E170506T172810ZOkx
019Cubix170509T031701ZMickyT
011APL Dyalog with AGL170508T091624ZAdá
061Swift170509T071045ZSamaira
023brainfuck170509T021639ZNitrodon
012Alice170508T162519ZLeo
038brainfuck170508T155050ZDoorknob
nan170508T154114Zauhmaan
005Jelly170507T025326ZDennis
060Java170507T123429ZKhaled.K
046Javascript ES6170508T073745ZWeedoze
030JavaScript ES6170508T092729ZShaggy
021Mathematica170506T171340ZGreg Mar
050PowerShell170507T191332ZAndrei O
049C170507T091021Z2501
009V170507T071901ZDJMcMayh
017Alice170506T180601ZMartin E
036R170507T015645Zflodel
030Ruby170507T002412ZCyoce
010CJam170507T000158ZEsolangi
151sed170506T213646ZRyan McC
044Python 3170506T213212ZDennis
033Hexagony170506T210647ZFryAmThe
140Batch170506T204828ZNeil
008Japt170506T200940ZETHprodu
040PHP170506T174246ZJör
036Haskell170506T182103Znimi
053C170506T180642Zbetseg
005MATL170506T180024ZLuis Men
00805AB1E170506T172211ZErik the
008Brachylog170506T172440ZFatalize
nan170506T172257ZBrad Gil
007Pyth170506T170611ZLeaky Nu
047Python 2170506T171336Zovs
006Jelly170506T170530ZErik the
011Retina170506T170919ZFryAmThe

Julia 1.0, 34 bytes

p->replace(p,r"((.)\2*)"=>s"\2\1")

Try it online!

Used regex from this answer: it catches the first character in the group of the same symbols and adds it to the group.

Vyxal, 9 bytes (Try it)

øeƛ÷›";ød

Arturo, 30 bytes

$=>[replace&{/((.)\2*)}"$1$2"]

Try it!

Non-regex answer:

Arturo, 38 bytes

$=>[chunk&=>[&]|map'x->x++x\0|flatten]

Try it!

Thunno 2 J, 3 bytes

ġ€ẹ

Try it online!

Explanation

ġ€ẹ  # Implicit input
ġ    # Group consecutive
 €   # Single function map:
  ẹ  #  Enclose (append
     #  first character)
     # Join into a string
     # Implicit output

Prolog (SWI), 51 bytes

\A:-get(C),C>0,(C=A;A<1;put(A)),put(C),\C;!.
:- \0.

Try it online!

Vyxal d, 3 bytes

ĠvǏ

Try it Online!

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

γ€ĆJ

has been replaced by γ in the latest update.

Cubix, 19 23 bytes

A.?@WW>o-!wu;W>1$o;

Try it online!

    A .
    ? @
W W > o - ! w u
; W > 1 $ o ; .
    . .
    . .

I think I can take a couple of this yet, but running out of steam and will probably come back to this later. General algorithm hasn't changed much, just the program flow.

APL (Dyalog) with AGL, 11 bytes

⊢é⍨2-0,2=/,

Try it online!

, ravel*

2=/ pair-wise comparison (shows which characters to leave as-is)

0, prepend a zero (indicating that the initial character should be duplicated)

2- subtract that from two (gives 2 for the letters which need to be duplicated, and 1 for the rest)

⊢é⍨ replicate the argument using that (é is just the function /)


* This is a no-op on strings, but makes scalar characters into strings. Not required, as argument should be a string, but it makes the tests look neater, and we need a no-op function here anyway. To remove this feature, use instead of ,.

Swift, 61 bytes

var b="ab".characters.map {"\($0)"},c="";for a in b{c=c+a+a;}

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
]

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.

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
]

C#, 115 bytes


Data


Golfed

(string i)=>{var t=' ';for(int x=0;x<i.Length;x++)if(i[x]!=t){i=i.Insert(x,t+"");t=i[x+1];}i=i.Trim()+t;return i;};

Ungolfed

( string i ) => {
   var t = ' ';
   
   for( int x = 0; x < i.Length; x++ )
      if( i[ x ] != t ) {
         i = i.Insert( x, t + "" );
         t = i[ x + 1 ];
      }
      
   i = i.Trim() + t;
      
   return i;
};

Ungolfed readable

// Takes a string to be stretched
( string i ) => {

   // Creates a temp var to hold the chars
   var t = ' ';
   
   // Cycles through every char in the string
   for( int x = 0; x < i.Length; x++ )
   
      // Checks if the temp var is different to the current one
      if( i[ x ] != t ) {
         
         // If so, insert a new char in the middle
         i = i.Insert( x, t + "" );
         
         // Stores the new char
         t = i[ x + 1 ];
      }
      
   // Removes the trailling space added due to the temp var
   i = i.Trim() + t;
      
   // Return the stretched string
   return i;
};

Full code

using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<String, String> f = ( int[] i ) => {
            var t = ' ';
            
            for( int x = 0; x < i.Length; x++ )
               if( i[ x ] != t ) {
                  i = i.Insert( x, t + "" );
                  t = i[ x + 1 ];
               }
               
            i = i.Trim() + t;
               
            return i;
         };

         List<String>
            testCases = new List<String>() {
               "a",
               "ab",
               "aab",
               "abcdvaabb",
               "aasd231",
               "",
            };

         foreach( String testCase in testCases ) {
            Console.WriteLine( $" Input: {testCase}\nOutput: {f( testCase )}\n" );
         }

         Console.ReadLine();
      }
   }
}

Releases


Notes

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.

Java, 151 146 60 bytes

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

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

Javascript ES6, 56 46 bytes

b=>[...b].map((c,i,a)=>a[i+1]!=c?c+c:c).join``

Saved 10 bytes thanks to @Shaggy using spread operator and c+c


Try it

f=

b=>[...b].map((c,i,a)=>a[i+1]!=c?c+c:c).join``

console.log(f("aabbcccc")); //aaabbbccccc
console.log(f("uuuuuuuuuz")); //uuuuuuuuuuzz
console.log(f("q")); //qq
console.log(f("xyxyxy")); //xxyyxxyyxxyy
console.log(f("xxxyyy")); //xxxxyyyy

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>

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.

PowerShell, 50 bytes

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

Try it online!

C, 49 bytes

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

See it work online.

V, 9 bytes

ͨ.©±*/&±

Try it online!

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.

R, 36 bytes

gsub("((.)\\1*)","\\2\\1",scan(,""))

Ruby, 30 bytes

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

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

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

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

Original solution

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

Python 3, 44 bytes

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

Try it online!

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)

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.

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

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

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.

C, 53 bytes

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

Try it online!

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'

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

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"

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

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

Python 2, 47 bytes

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

Try it online!

Jelly, 6 bytes

Œg;Q$€

Try it online!

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

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.