# Repeat every other character in string starting with second character

Requirements:

• Take a single word as input with only lowercase alphabetical characters (a-z)
• Output a string where every other character is repeated, with the first repeated character being the second character in the string

Example:

Input: abcde

Output: abbcdde

Winning Criteria:
Standard code golf. Shortest number of bytes in program wins.

Clarification:
For languages with 1-based indexing the output must still match the above, aabccdee is not an acceptable solution.

• May we start from 1 as the first character, for the benefit of languages with 1-based indexing? – Shaggy Feb 1 at 0:08
• Sure, i just called the first character 0th so my title "repeat odd index characters" makes sense. As long as you the output is repeating "Every other" character starting from the second character I the string (which I call index 1) then it's acceptable – Taako Feb 1 at 0:10
• I suggest you use standard I/O rules instead of requesting to use stdin (and never saying to use stdout, by the way). Or is there some reason to avoid it? – val says Reinstate Monica Feb 1 at 20:23
• Also, python answer is already a function that actually uses argument for input and return for output, so I'm assuming that you actually allow default I/O ways and are not restricting to stdin. – val says Reinstate Monica Feb 1 at 20:31
• @Neyt "Every other" is an English phrase that could mean all but one exception but in this case it does not. It is similar to "alternating", for example "every other day" means "either all even days and no odd days or all odd days and no even days". I don't think there is really any logic to it. If you are still confused the ESL stack exchange is probably the place to ask about this further. – Wheat Wizard Feb 3 at 16:52

# Lua, 34 bytes

print(((...):gsub('.(.)','%0%1')))


Try it online!

Takes input as an argument, prints result to stdout. Every two characters are replaced with themselves and second one appended.

# Perl 6, 14 bytes

{S:g[.<(.]x=2}


Try it online!

Regex that matches every other character and substitutes it with itself string multiplied by 2.

# PHP, 37 bytes

while($c=$argn[$i++])echo$c,$c[$i%2];


Try it online!

# naz, 44 bytes

2a2x1v1x1f1r3x1v2e1o1r3x1v2e2o1f0x1x2f0a0x1f


Works for any input string terminated with the control character STX (U+0002).

Explanation (with 0x commands removed)

2a2x1v                     # Set variable 1 equal to 2
1x1f1r3x1v2e               # Function 1
# Read a byte of input
1o             # Otherwise, output it once
1r3x1v2e     # Read another byte of input
2o   # Otherwise, output it twice
1f # Jump back to the start of function 1
1x2f0a                     # Function 2
# Add 0 to the register
1f                         # Call function 1


# Whitespace, 66 bytes

[S S S T    N
_Push_1][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S S _Add][S S S T S N
_Push_2][T  S T T   _Modulo][S N
S _Dupe][S N
S _Dupe][S N
S _Dupe][S N
S _Dupe][T  N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][T  N
S S _Print_as_character][N
T   S N
_If_0_Jump_to_Label_LOOP][T T   T   _Retrieve_input][T  N
S S _Print_as_character][N
S N
N
_Jump_to_label_LOOP]


Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer n = 1
Start LOOP:
n = (n+1) modulo-2
Integer c = STDIN as character
Print c as character to STDOUT
If(n == 0):
Go to the next iteration of LOOP
Print c as character to STDOUT
Go to the next iteration of LOOP

• I really would like to master loops and conditional in WhiteSpace. Haven't quite been able to get one working yet. – ouflak Feb 6 at 17:27
• @ouflak I can certainly recommend to use the vii5ard compiler when you're developing in Whitespace. It allows you to debug through the code, and see the values on the stack and heap in the memory-tab. You can even set breakpoints. Also, maybe the more in-depth explanation in this Whitespace interpreter challenge of mine might clarify a thing or two in comparison to the tutorial linked in the title. – Kevin Cruijssen Feb 6 at 17:53
• @ouflak For a loop you basically mark a location with a Label, and you Jump to that label later on. Here for example an infinite loop printing a 1 every iteration: NSSN SSSTN TNST NSNN (create label (empty); push 1; pop and print as integer; jump to label (empty)). For an if-statement you'd have to make the value either 0 or negative, and use the conditional jumps. You usually do have to duplicate the value if you still need it later on however, since the conditional labels will pop the value. – Kevin Cruijssen Feb 6 at 17:55
• @ouflak If you have any questions in particular, or want me to turn a provided pseudo-code into a Whitespace program with explanation, feel free to contact me again. PS: Unfortunately you can't save / link from the vii5ard compiler, which is why I have TIO links in my answers. I never create the programs in TIO though, always in vii5ard. – Kevin Cruijssen Feb 6 at 17:56

# Perl 5-p, 13 bytes

s/.\K./$&$&/g


Try it online!

# JavaScript (V8), 76685648 44 bytes

Thanks to Malivil for 12 bytes !

s=>s.split.map((v,i)=>i%2==1?v+v:v).join


Try it online!

• Welcome to the site. Your submission seems to take input by inserting it into the code. The challenge requires that input be taken from standard in that would be the input field on TIO. – Wheat Wizard Feb 3 at 16:39
• @PostRockGarfHunter Sorry about that, i've added an edited version. – Nicolas Feb 3 at 16:40
• You can save a few more bytes by changing v.repeat(2) to v+v – Malivil Feb 3 at 16:48
• Actually you can save more by using the newer syntax for those empty string functions, like this – Malivil Feb 3 at 16:54
• 38 bytes: s=>[...s].map((v,i)=>i%2?v+v:v).join – Chau Giang Feb 5 at 9:38

# brainfuck, 18 bytes

>,[>,]<[<]>[.>..>]


Requires 0-termination for EOF. Prints two trailing null bytes for odd-length strings.

Try it online!

• You should fix your answer rather than leave it invalid. – Jo King Feb 3 at 22:14
• @JoKing Still figuring that out :). – S.S. Anne Feb 3 at 22:16

# PowerShell, 26 bytes

$args-replace'.(.)','$0$1'  Try it online! # Burlesque, 11 bytes 2co{J[-j}\m  Try it online! 2co # Split into chunks of 2 {"ab" "cd" "e"} { J # Duplicate pair of chars [- # Take the tail (returns empty for length 1 strings) j # Swap to correct order for concat }\m # For each pair, and then concatenate  # Burlesque, 8 bytes 2co)+.\[  Try it online! Works for even length strings only 2co # Same as above )+. # For each group append the last char again \[ # Concatenate  # APL (Dyalog), 12 11 bytes -1 byte thanks to Bubbler ∊⊢⍴⍨¨1 2⍴⍨≢  Try it online! A train that takes a string and returns a string (or any list technically). ### Explanation:  ⍴⍨ ⍝ Reshape ¨ ⍝ Each of ⊢ ⍝ The input 1 2 ⍝ To the array 1 2 ⍴⍨ ⍝ Reshaped to ≢ ⍝ The length of the input ∊ ⍝ And flatten the result  # .+?, 11 bytes (.(.)) \1\2  The first answer in my new language. It's a simple language based around python regex substitution # Explanation (.(.)) Replace each pair of characters with \1\2 matching group 1 (both characters) followed by matching group 2 (the second character)  Try it online! (The second command line argument is input) • Nice approach! Isn't \0/$0 possible in Python or your language? I.e. .(.) and \0\1? – Kevin Cruijssen Feb 20 at 16:37
• Sadly not, python's regexes are pretty limited compared to most other flavours – EdgyNerd Feb 20 at 16:42

# C (gcc), 66 $$\\cdots\$$ 59 57 bytes

Saved a 3 bytes thanks to ceilingcat!!!
Saved a byte thanks to S.S. Anne!!!

i;f(c){for(i=0;~(c=getchar());printf(&c))c*=i++%2?257:1;}


Try it online!

• Save another by swapping c and i and initializing i at its definition. – S.S. Anne Feb 3 at 17:29
• @S.S.Anne Nice one - thanks! :-) – Noodle9 Feb 3 at 18:06
• @ceilingcat Nice one - thanks! :-) – Noodle9 Jul 25 at 14:02

## @, 13 bytes

¤+ōČōōČ


## Explanation

  ōČ    Take a character and print it.
ōōČ Take a character and print it twice.
¤+      Repeat this forever.


# Funky, 34 bytes

s=>fori=0i<#s i++write(s[i]*1+i%2)


A pretty simple solution to the problem.

Try it online!

# Charcoal, 8 bytes

⭆Ｓ×ι⊕﹪κ²


Try it online! Link is to verbose version of code. Explanation:

 Ｓ          Input string
⭆           Map over characters and join
²    Literal 2
κ     Current index
﹪      Modulo
⊕       Incremented
ι        Current character
×         Repeated
Implicitly print


# APL+WIN, 13 bytes

Prompts for string:

((⍴s)⍴⍳2)/s←⎕


Try it online! Courtesy of Dyalog Classic.

# SimpleTemplate, 44 bytes

This was easy, but also fun!

{@eachargv.0}{@echo_}{@if__ is mod2}{@echo_}


Loops through all the characters, and checks if the index of the character (__) is not a multiple of 2 (odd). If it isn't a multiple of 2, outputs it again.

Ungolfed:

Just in case you are curious.

{@each argv.0 as char key key}
{@echo char}
{@if key is not multiple of 2}
{@echo char}
{@/}
{@/}

• The as char is optional, using the variable _ by default, to hold the array item/character from the string.
• The key key is optional, using the variable __ by default, to hold the index.
• All the {@/} ae optional and safe to remove.

You can try it on http://sandbox.onlinephpfunctions.com/code/5fc880374f58b72c4dc3ee2c573349e7a218aed8 You can check and try both golfed and ungolfed versions.

# C (gcc), 49 48 bytes

-1 thanks to ceilingcat

M;f(c){++M%3?c=getchar():0;M=~c&&f(putchar(c));}


Try it online!

i=1;f(c){for(;-~(c=getchar());i^=1)printf("%c%1$c"+i*2,c);}  Using original input rules. Try it online! # C (gcc), 54 bytes i=1;f(char*s){for(;*s;i^=1)printf("%c%1$c"+i*2,*s++);}


Using acceptable input.

Try it online!

Assuming your string are all alphabetically sorted, you can use:

# Python 3, 42 bytes:

lambda x:''.join(sorted(x[1::2]*2+x[::2]))


Try it online!

# PowerShell, 102 bytes

function b($i){$c=0;$o;$i.ToCharArray().ForEach{if($c%2-eq1){$o+="$_$_"}else{$o+="$_"}$c++;};write$o}


Try it online!

## Unix TMG, 59 bytes

p:parse((c={1}))parse((c={1 1}))\p;c:smark any(!<<>>)scopy;


# CJam, 12 bytes

q2/{_La+1=}%


Try it online!

## Explanation

q2/{_La+1=}%
q2/           Read the input and split it into groups of 2 characters.
{      }%  For each group:
_           Copy it.
La+        Append an empty string.
1=      Get its second element.
Join the results.


# Z80Golf, 12 bytes

00000000: d52e 76e5 2e07 e5cd 0380 38f6            ..v.......8.


Try it online!

  push de
Z:ld l, $76 push hl ld l, G push hl G:call$8003
jr c, Z+1   ; halt on EOF, else fallthrough


# Explanation

Z80golf is a small Z80 computer hooked up to $8000=putchar,$8003=getchar. (putchar prints byte A; getchar reads a byte into A or sets the carry flag on EOF.) Our code is placed at $0000 and all registers start at 0, including PC. The rest of memory is filled with zeroes. Let's run through some sample input: uvwxyz. We push three addresses to the stack: $0000, then $0076, then G. Then (here's label G), we call getchar(), and on EOF jump to the HALT instruction ($76) hidden in the argument to ld l, $76. Otherwise, control flow falls through a sea of NOPs into $8000. This is hardcoded to perform putchar(A); ret, so we print u and return back to G.

The next time we get here, we print v and return to $0076, amid the NOP sea: control flow runs back to $8000, we print v again, then return to \$0000, where the code starts over.

Repeating this process, the output is uvvwxxyzz → HALT.

# Forth (gforth), 46 bytes

: f 0 do dup dup 1 type i 2 mod type 1+ loop ;


Try it online!

### Code Explanation

: f              \ start a new word definition
0 do           \ loop from 0 to string-len - 1
dup dup      \ duplicate the current character address twice
1 type       \ output the current letter
i 2 mod type \ if odd, output again, if even do nothing (0 type = output nothing)
1+           \ increment current character address
loop           \ end loop
;                \ end word definition


# GolfScript, 9 bytes

2/{1/~.}%

2/{1/~.}% #Repeat every other character
2/        #Split string into bits of size 2
{    }% #For every of those elements, do block
{1/  }  #Divide into elements of size 1
{  ~ }  #Pop from their array
{   .}  #Duplicate the last element


Probably possible to shave a byte or two by refining the block. Unfortunately ) doesn't decouple properly.

Try it online!

# Chevron - 96 bytes

>^__>^a
^a~s>>^s
^__>^n
0>>^i
^i+1>>^i
->+6?^i>^s
^a,^i~c>>^l
^n^l>^n
->-4?^i~o
^n^l>^n
->-6
>^n


# Pyth, 98 7 bytes

And of course, the simple solution always prevails, and comes to me after I thought I'd done something clever :/

-1 byte because I literally put my laptop away and then remembered that s was a thing

%2ts*L3


Explanation:

%2tjk*L3
# Implicit Q = eval(input())
%2        # Every second character of:
t       #   All but the first character of:
jk     #     Joined on the empty string:
*L3  #       Each character of Q * 3


## Previous version (9 bytes)

r9m,h=!Td


Falling behind a lot of other golfing languages unfortunately

Explanation:

           # Implicit T=10, Q=eval(input())
r9         # Run length decode
m        # map over (implicit) Q
,h=!Td  # create a pair of:
h=!T   # 1 + (T = not T) and
d  # the character


Try it online!

# T-SQL, 88 bytes

DECLARE @x INT=len(@)/2*2WHILE @x>0SELECT
@=stuff(@,@x,0,substring(@,@x,1)),@x-=2PRINT @


Try it online