27
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ May we start from 1 as the first character, for the benefit of languages with 1-based indexing? \$\endgroup\$ – Shaggy Feb 1 at 0:08
  • \$\begingroup\$ 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 \$\endgroup\$ – Taako Feb 1 at 0:10
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – val says Reinstate Monica Feb 1 at 20:23
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – val says Reinstate Monica Feb 1 at 20:31
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ – Post Rock Garf Hunter Feb 3 at 16:52

66 Answers 66

11
\$\begingroup\$

Jelly, 3 bytes

ḤÐe

A full program accepting a string which prints the result

Try it online!

How?

Utilises the fact that the implementation of the double atom, , is multiplication by two, and that strings are lists of Python characters. In Python when a character is multiplied by two it becomes a Python string of length two (e.g. 'x'*2=='xx'). Lastly the implicit output of a list composed entirely of characters and strings (or lists thereof) is its content all smashed together.

ḤÐe - Main Link: list of characters  e.g. input abcd -> ['a','b','c','d']
 Ðe - apply to even indices (1-indexed):
Ḥ   -   multiply by 2                     -> ['a', 'bb', 'c', 'dd']
    - implicit, smashing print            -> abbcdd
\$\endgroup\$
16
\$\begingroup\$

sed, 12

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

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ This is really lovely \$\endgroup\$ – Jonah Feb 1 at 0:34
12
\$\begingroup\$

brainfuck, 13 or 11 bytes

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

Assumes EOF->0. :(

You can try it online!

(Assuming input also continues to give zeroes indefinitely after the first EOF, we can do it in 11 bytes:

,[.,[..>],]

though this eats memory.)

\$\endgroup\$
  • 1
    \$\begingroup\$ You may assume infinite time and memory for the purposes of code golf. \$\endgroup\$ – Shaggy Feb 1 at 10:03
  • \$\begingroup\$ I don't necessarily agree with the "infinite time and memory" because BOGO sorting would be "allowed", which would be ridiculous. Imagine if a "check if a string is an anagram of another string" formula was "shuffle the second string, compare, and continue if unequal. If 2^n days have passed, where n is the length of the string, consider the strings non-anagrams". It would have an error rate less than the expected failure of a CPU while running a typical program. \$\endgroup\$ – Mathgeek Feb 14 at 14:23
10
\$\begingroup\$

Python, 38 bytes

f=lambda s:s and s[:2]+s[1:2]+f(s[2:])

Try it online!

Takes the first two characters, then the second character, then removes the first two characters and recurses.


39 bytes

f=lambda s,c=2:s and s[:c]+f(s[1:],3-c)

Try it online!

Flips between taking the first two or first one character.

\$\endgroup\$
  • \$\begingroup\$ I really like these two answers, tbh \$\endgroup\$ – RGS Feb 1 at 0:21
  • \$\begingroup\$ Oh, nice; two at a time! \$\endgroup\$ – Jonathan Allan Feb 1 at 2:02
  • \$\begingroup\$ I posted a 37 byte answer. \$\endgroup\$ – Lynn Feb 19 at 18:39
10
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 14 bytes

Binary:

00000000: b401 cd21 f7d9 78f8 b40e cd10 ebf2       ...!..x.......

Unassembled:

    START: 
B4 01   MOV  AH, 1      ; DOS read char from STDIN 
CD 21   INT  21H        ; put char in AL 
F7 D9   NEG  CX         ; toggle CX sign
78 F8   JS   START      ; if negative, loop to next char 
B4 0E   MOV  AH, 0EH    ; BIOS write char to console
CD 10   INT  10H        ; write char to screen again 
EB F1   JMP  START      ; loop until break/^C

A standalone executable DOS program. Input via STDIN (pipe or keyboard interactive), output to STDOUT.

Output:

enter image description here

\$\endgroup\$
7
\$\begingroup\$

Haskell, 33 24 bytes

By noticing that obviously f [] = [] also fits the pattern f s = s and removing one extra space, we get to

f(a:b:s)=a:b:b:f s
f s=s

from my starting point of

f []=[]
f (a:b:s)=a:b:b:f s
f s=s

Now my answer matches xnor's Haskell answer.

You can try it online!.

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

J, 8 bytes

#~1 2$~#

Try it online!

  • 1 2$~# Shape $~ the list 1 2 (repeating it cyclically as needed) until it matches the length # of the input.
  • #~ Use this 1 2 1 2... "mask" to Copy #~ the implicit input elementwise. That is, make 1 copy of the first char, 2 copies of the 2nd char, 1 copy of the third char, etc.
\$\endgroup\$
6
\$\begingroup\$

Haskell, 24 bytes

f(a:b:t)=a:b:b:f t
f s=s

Try it online!

\$\endgroup\$
  • \$\begingroup\$ This feels pretty similar to mine and now I feel stupid if I don't golf mine further. But then we'll have equal answers... So what now? \$\endgroup\$ – RGS Feb 1 at 0:20
  • 3
    \$\begingroup\$ @RGS That's fine, go for it. Duplicate answers come up a fair bit here and are a good sign that the mutually found solution is indeed well-golfed. \$\endgroup\$ – xnor Feb 1 at 0:23
6
\$\begingroup\$

Octave / MATLAB, 16 bytes

@(s)s(1:2/3:end)

Try it online!

Explanation

Non-integer values are automatically rounded (with a warning) in colon index expressions.

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

Python 2, 34 bytes (xnor's improvement)

lambda s:`[c*11for c in s]`[7::10]

Try it online!

Python 2, 36 bytes

lambda s:`sum(zip(s,s,s),())`[7::10]

Try it online!

Slices characters 7, 17, 27… out of a string like this:

('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'e', 'e', 'e')
012345678901234567890123456789012345678901234567890123456789012345678901234
       ^         ^         ^         ^         ^         ^         ^
→ abbcdde

xnor's c*11 trick achieves the same thing, but with a string like:

['aaaaaaaaaaa', 'bbbbbbbbbbb', 'ccccccccccc', 'ddddddddddd', 'eeeeeeeeeee']
012345678901234567890123456789012345678901234567890123456789012345678901234
       ^         ^         ^         ^         ^         ^         ^
→ abbcdde

Python 3, 37 bytes

lambda s:''.join(c*3for c in s)[1::2]

Try it online!

If returning a tuple of characters is OK (which it isn't), lambda s:sum(zip(s,s,s),())[1::2] is a 33-byte solution.

\$\endgroup\$
  • \$\begingroup\$ What a clever idea! I've posted a bounty and will keep it up for the week. \$\endgroup\$ – xnor Feb 22 at 10:39
  • 1
    \$\begingroup\$ It looks like you can save more bytes with a different string to slice, though interestingly also sliced [7::10]: TIO \$\endgroup\$ – xnor Feb 22 at 10:43
4
\$\begingroup\$

Japt -m, 4 bytes

+pVu

Try it

+pVu     :Implicitly map each character U at 0-based index V in the implicit input string
+        :Append to U
 p       :U repeated
  Vu     :  V mod 2 times
         :Implicit output of resulting string
\$\endgroup\$
  • \$\begingroup\$ What does the -m flag do? \$\endgroup\$ – S.S. Anne Feb 4 at 17:44
  • 1
    \$\begingroup\$ @S.S.Anne, it enables the implicit map mentioned in the explanation. \$\endgroup\$ – Shaggy Feb 4 at 18:17
4
\$\begingroup\$

Brainfuck, 52 31 bytes

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

You can try it online or you can check my first submission, that I think is also simpler to understand:

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

Cell layout is

| 1 | aux | mult | inp | mult |

where mult is the number of extra times we have to print the current character. Feel free to drop me a line in the comments with feedback.

Try it online!

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

Scratch 3.0, 25 blocks/179 bytes

Blocks

As SB Syntax:

define f(n
set[i v]to(1
set[o v]to(
repeat((length of(n))/(2
set[o v]to(join(o)(letter(i)of(n
change[i v]by(1
set[x v]to(letter(i)of(n
set[o v]to(join(o)(join(x)(x
change[i v]by(1

Oh boy, here I go Scratching again! This was quite an interesting one to solve, and I quite enjoyed it. Thanks for the challenge.

The output of the function is shown in the top left corner.

Finally, Try it online Scratch!

\$\endgroup\$
  • 2
    \$\begingroup\$ I really like this. Thabk you for the submission \$\endgroup\$ – Taako Feb 1 at 4:05
  • \$\begingroup\$ 124 bytes.TIO block syntax:scratchblocks.github.io/… \$\endgroup\$ – user85052 Feb 1 at 10:20
4
\$\begingroup\$

Shakespeare Programming Language, 126 bytes

,.Ajax,.Page,.Act I:.Scene I:.[Exeunt][Enter Page and Ajax]Ajax:Open mind.Speak thy.Open mind.Speak thy.Speak thy.Let usAct I.

Try it online!

Page reads the input one character at a time, and alternately prints it once or twice. Exits with error after printing the correct output.

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

Unreadable, 43 bytes

'"""""'"""'""""'"'""""""""""'"'"'""""""""""

Try it online!

Displayed here in variable-width font, per the traditional tribute to the language name.

Exits with error after printing the correct output.

Explanation:

'"""""'"""      while(1)
'""""           do 2 things:
'"'""""""""""   print(read stdin)
'"'"'"""""""""" print(print(read stdin))

Uses the fact that '" both prints and returns its argument, which can thus be directly fed to a 2nd print command.

\$\endgroup\$
  • 1
    \$\begingroup\$ That's definitely unreadable. \$\endgroup\$ – S.S. Anne Feb 4 at 19:00
4
\$\begingroup\$

Python 3,  43 41  39 bytes

-2 thanks to mypetition (s[:1]*i can be s[:i] if we swap our order of is)

f=lambda s,i=2:s and s[:i]+f(s[1:],i^3)

A recursive function which accepts a string and returns a string.
Works in Python 2 too.

Try it online!

At each call we return s if it is empty or take the first up-to-i-characters of the given string (s[:i]) where i starts out as 2 and append (+) the result of another call to the function this time using a new s of all but the first character (s[1:]) and a new i found by XOR-ing with three (i^3) - i.e. 2, 1, 2, 1, ...

\$\endgroup\$
  • 1
    \$\begingroup\$ Really clever way of switching between 1 and 2! \$\endgroup\$ – RGS Jan 31 at 23:57
  • \$\begingroup\$ f=lambda s,i=2:s and s[:i]+f(s[1:],i^3) saves 2 bytes \$\endgroup\$ – mypetlion Feb 3 at 18:36
  • \$\begingroup\$ @mypetlion Good golf, thanks! \$\endgroup\$ – Jonathan Allan Feb 3 at 19:05
  • \$\begingroup\$ @mypetlion ...and it's just a short step from there to realising we can drop i entirely, which gives xnors f=lambda s:s and s[:2]+s[1:2]+f(s[2:]). \$\endgroup\$ – Jonathan Allan Feb 3 at 19:11
3
\$\begingroup\$

Python 3, 54 50 49 bytes

This looks incredibly long, I have no idea if something obvious is slipping under my nose... And already saved 5 bytes thanks to @Jonathan Allan! Check his 43 byte Python 3 answer! but here it is:

lambda s:''.join(c+i%2*c for i,c in enumerate(s))

You can try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Save 2 with enumerate and 2 more by using a generator (dropping the []) - TIO \$\endgroup\$ – Jonathan Allan Feb 1 at 0:03
  • \$\begingroup\$ @JonathanAllan thanks for the tip! \$\endgroup\$ – RGS Feb 1 at 0:10
  • 1
    \$\begingroup\$ Oh, another 1 by distributing over the addition and reordering to avoid % being treated as a format instruction: c*(1+i%2)->i%2*c+c (or c+i%2*c) \$\endgroup\$ – Jonathan Allan Feb 1 at 0:15
3
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 84 bytes

	S =INPUT
S	S LEN(1) . L LEN(1) . R REM . S	:F(O)
	O =O L R R :(S)
O	OUTPUT =O S
END

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Oh, nice! A fellow Bell Labs language. \$\endgroup\$ – Andriy Makukha Feb 2 at 19:26
3
\$\begingroup\$

Keg -ir -lp, 4 bytes

(,⑩,

Try it online!

Explanation

     # (Implicitly) take an input from the console
(    # For every item in the input:
 ,   # Print the first character, popping the stack
  ⑩  # Print the top of the stack w/o poping
   , # Print with popping, effectively doubling the second character
\$\endgroup\$
3
\$\begingroup\$

k4, 17 bytes

{,/#'[(#x)#1 2]x}

{               } /lambda with implicit arg x
      (#x)        /count x
          #1 2    /takes #x items of 1 2
   #'[        ]x  /take [...] items of x
 ,/               /flatten
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 5 bytes

āÈ>×J

Input as a list of characters, which is allowed by default.

I have the feeling 4 bytes might be possible, but I'm unable to find it.

Try it online.

Explanation:

ā      # Take the (implicit) input-list, and push a list in the range [1, input-length]
       #  i.e. ["a","b","c","d","e"] → [1,2,3,4,5]
 È     # Check for each value in this list whether it's even (1 if truthy; 0 if falsey)
       #  → [0,1,0,1,0]
  >    # Increase each value by 1 (thus 2 if truthy; 1 if falsey)
       #  → [1,2,1,2,1]
   ×   # Repeat each character in the input-list that many times
       #  → ["a","bb","c","dd","e"]
    J  # And join the list together to a single string
       #  → "abbcdde"
       # (after which this is output implicitly)
\$\endgroup\$
3
\$\begingroup\$

Ruby, 25 bytes

->s{s.gsub /.(.)/,'\0\1'}

Try it online!

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

brainfuck, 13 bytes

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

Try it online!

Handles odd and even length strings correctly. This takes an input and prints it once before checking if the previous cell contains the previous character. If so, it prints again and moves three spaces ahead, otherwise it just moves one cell ahead, and then it gets the next character.

\$\endgroup\$
  • \$\begingroup\$ This requires cells to the left of the tape. \$\endgroup\$ – S.S. Anne Feb 3 at 22:21
  • 1
    \$\begingroup\$ @S.S.Anne While it is non-standard, multiple interpreters support it, including the ones on TIO and copy.sh (IIRC). \$\endgroup\$ – Bubbler Feb 3 at 23:32
3
\$\begingroup\$

PowerShell, 40 38 37 bytes

-join($args|% t*y|%{"$_"*(1+$i++%2)})

Try it online!

Takes input $args, transforms it toCharArray, pipes that into a loop. Each iteration, we repeat the character "$_" either 1 or 2 times based on a modulo-index. Those characters/strings are left on the pipeline, gathered up with a -join to turn it back into a single string, and output is implicit.

-2 bytes thanks to Veskah.
-1 byte thanks to mazzy.

\$\endgroup\$
  • \$\begingroup\$ Pretty sure you don't need quotes around $args for 38 bytes \$\endgroup\$ – Veskah Feb 3 at 14:38
  • 1
    \$\begingroup\$ @Veskah Thanks - that was a leftover from when I was originally writing the submission. \$\endgroup\$ – AdmBorkBork Feb 3 at 14:41
  • \$\begingroup\$ one more 37 bytes \$\endgroup\$ – mazzy Feb 4 at 7:28
  • \$\begingroup\$ @mazzy Clever. Thanks! \$\endgroup\$ – AdmBorkBork Feb 4 at 13:57
2
\$\begingroup\$

Hexagony, 13 12 bytes

,.<>,;/@/$;*

Try it online!

Expanded

  , . <
 > , ; /
@ / $ ; *
 . . . .
  . . .

Uses the very naive read-print, read-print twice approach.

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

Red, 51 bytes

func[s][foreach[a b]s[prin rejoin[a t: any[b""]t]]]

Try it online!

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

W d, 6 bytes

♀J,⌡I►

Uncompressed:

2V2m-*M

Explanation

Not a really good target for this challenge, I just feel that this is pretty fun to do.

Also the 1-indexed advantage seems to be a disadvantage here. If only W has a 0-index ...

% Note that W is one-indexed. (For the ease of the iterator protocols
% which have a 1-range as a built-in.)
 V2m    % Index of current item modulo 2
2   -   % Subtract 2 by the number (effectively yields
        % 1->1, 0->2 )
     *  % Repeat the character that many times
      M % Do this for every item in the input
\$\endgroup\$
2
\$\begingroup\$

GolfScript, 16 bytes

GolfScript doesn't have item count so you will need to do it yourself.

1:&;{]&):&2%)*}%

Try it online!

Explanation

# Implicitly pushed input
1:&;             # set count to 1
    {         }% # foreach item of input
     ]&):&       #     add count by one
          2%)*   #     repeat item by cnt % 2 + 1
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 28 bytes

Uses the same regex as @DigitalTrauma.

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

Try it online!


JavaScript (ES6), 32 bytes

A recursive version.

f=([a,b,...c])=>b?a+b+b+f(c):[a]

Try it online!

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

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.

\$\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.