33
\$\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\$
13
  • \$\begingroup\$ May we start from 1 as the first character, for the benefit of languages with 1-based indexing? \$\endgroup\$
    – Shaggy
    Feb 1, 2020 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, 2020 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\$ Feb 1, 2020 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\$ Feb 1, 2020 at 20:31
  • 2
    \$\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\$
    – Wheat Wizard
    Feb 3, 2020 at 16:52

83 Answers 83

18
\$\begingroup\$

sed, 12

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

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is really lovely \$\endgroup\$
    – Jonah
    Feb 1, 2020 at 0:34
14
\$\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\$
3
  • 2
    \$\begingroup\$ You may assume infinite time and memory for the purposes of code golf. \$\endgroup\$
    – Shaggy
    Feb 1, 2020 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, 2020 at 14:23
  • 2
    \$\begingroup\$ @Mathgeek CPU failure is not usually a consideration for code golf, whereas program determinism is. And the expected runtime for Bogosort is O(n!), not O(2^n). \$\endgroup\$
    – user76284
    Feb 27, 2020 at 21:13
12
\$\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\$
0
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\$
3
  • \$\begingroup\$ I really like these two answers, tbh \$\endgroup\$
    – RGS
    Feb 1, 2020 at 0:21
  • \$\begingroup\$ Oh, nice; two at a time! \$\endgroup\$ Feb 1, 2020 at 2:02
  • \$\begingroup\$ I posted a 37 byte answer. \$\endgroup\$
    – Lynn
    Feb 19, 2020 at 18:39
10
\$\begingroup\$

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

Binary:

00000000: b401 cd21 f7d9 78f8 cd29 ebf4            ...!..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 
CD 29   INT  29H        ; DOS 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\$
9
+150
\$\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\$
2
  • \$\begingroup\$ What a clever idea! I've posted a bounty and will keep it up for the week. \$\endgroup\$
    – xnor
    Feb 22, 2020 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, 2020 at 10:43
7
\$\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\$
7
\$\begingroup\$

Haskell, 24 bytes

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

Try it online!

\$\endgroup\$
2
  • \$\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, 2020 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, 2020 at 0:23
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\$

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\$
6
\$\begingroup\$

CJam, 9 8 bytes

q3e*1>2%

Try it online!

Explanation

  abcde             q     read input
→ aaabbbcccdddeee   3e*   repeat characters x3
→  aabbbcccdddeee   1>    drop first 
→  a b b c d d e    2%    every other char

Esolanging Fruit saved 1 byte: 3f*s3e*.

\$\endgroup\$
2
  • \$\begingroup\$ Can you use 3e* instead of 3f*s? \$\endgroup\$ Mar 1, 2020 at 18:57
  • \$\begingroup\$ It seems so! Good eye. \$\endgroup\$
    – Lynn
    Mar 2, 2020 at 15:01
5
\$\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\$
2
  • \$\begingroup\$ What does the -m flag do? \$\endgroup\$
    – S.S. Anne
    Feb 4, 2020 at 17:44
  • 1
    \$\begingroup\$ @S.S.Anne, it enables the implicit map mentioned in the explanation. \$\endgroup\$
    – Shaggy
    Feb 4, 2020 at 18:17
5
\$\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
  • 4
    \$\begingroup\$ I really like this. Thabk you for the submission \$\endgroup\$
    – Taako
    Feb 1, 2020 at 4:05
  • \$\begingroup\$ 124 bytes.TIO block syntax:scratchblocks.github.io/… \$\endgroup\$
    – user85052
    Feb 1, 2020 at 10:20
5
\$\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
  • 1
    \$\begingroup\$ That's definitely unreadable. \$\endgroup\$
    – S.S. Anne
    Feb 4, 2020 at 19:00
5
\$\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\$
4
  • 1
    \$\begingroup\$ Really clever way of switching between 1 and 2! \$\endgroup\$
    – RGS
    Jan 31, 2020 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, 2020 at 18:36
  • \$\begingroup\$ @mypetlion Good golf, thanks! \$\endgroup\$ Feb 3, 2020 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\$ Feb 3, 2020 at 19:11
5
\$\begingroup\$

Vyxal, 5 3 bytes

3•y

Try it Online!

3•  # Repeat each character three times
  y # Get every other character
\$\endgroup\$
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\$

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

k4, 17 13 bytes

edit: make use of & (where operator) which for each index i of an int-list L give gives L[i] copies of i. eg &2 1 3 -> 0 0 1 2 2 2

{x@&(#x)#1 2}
{           } /lambda with implicit arg x
    (#x)      /count x
        #1 2  /takes #x items of 1 2 (eg 3#1 2 -> 1 2 1)
   &          /&1 2 1 -> 0 1 1 2 
 x@           /index x
\$\endgroup\$
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\$
3
  • 1
    \$\begingroup\$ Save 2 with enumerate and 2 more by using a generator (dropping the []) - TIO \$\endgroup\$ Feb 1, 2020 at 0:03
  • \$\begingroup\$ @JonathanAllan thanks for the tip! \$\endgroup\$
    – RGS
    Feb 1, 2020 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\$ Feb 1, 2020 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\$
1
  • \$\begingroup\$ Oh, nice! A fellow Bell Labs language. \$\endgroup\$ Feb 2, 2020 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\$
0
3
\$\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\$
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\$
2
  • \$\begingroup\$ This requires cells to the left of the tape. \$\endgroup\$
    – S.S. Anne
    Feb 3, 2020 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, 2020 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\$
4
  • \$\begingroup\$ Pretty sure you don't need quotes around $args for 38 bytes \$\endgroup\$
    – Veskah
    Feb 3, 2020 at 14:38
  • 1
    \$\begingroup\$ @Veskah Thanks - that was a leftover from when I was originally writing the submission. \$\endgroup\$ Feb 3, 2020 at 14:41
  • \$\begingroup\$ one more 37 bytes \$\endgroup\$
    – mazzy
    Feb 4, 2020 at 7:28
  • \$\begingroup\$ @mazzy Clever. Thanks! \$\endgroup\$ Feb 4, 2020 at 13:57
3
\$\begingroup\$

Ruby, 25 bytes

->s{s.scan(/(.(.?))/)*''}

Try it online!

Same byte count as the other answer, different approach.

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

Pip, 11 bytes

B X_%2+1MEa

Try it online!

-2 from Dlosc.

\$\endgroup\$
1
  • \$\begingroup\$ +1, very similar to my initial approach. You can use string repetition and a lambda expression to get down to 11 bytes: Try it online! (10 bytes in Pip 1.0 because _%2 -> %_.) \$\endgroup\$
    – DLosc
    Nov 9, 2021 at 22:11
3
\$\begingroup\$

05AB1E, 5 4 bytes

€Ðιθ

I/O 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.
It is possible, by porting @emanresuA's Vyxal answer (so make sure to upvote him/her as well).

Try it online.

Explanation:

      #  (example input = ["a","b","c","d","e"])
€Ð    # Triplicate each character (which remains a flattened list)
      #  → ["a","a","a","b","b","b","c","c","c","d","d","d","e","e","e"]
  ι   # Uninterleave this list into two parts
      #  → [["a","a","b","c","c","d","e","e"],["a","b","b","c","d","d","e"]]
   θ  # Pop and leave just the second part
      #  → ["a","b","b","c","d","d","e"]
      # (which is output implicitly as result)
\$\endgroup\$
3
\$\begingroup\$

Rockstar, 95 81 bytes

listen to S
cut S
Y's 1
O's ""
while S
let O be+roll S*Y
let Y be Y-1 or 2

say O

Try it here (Code will need to be pasted in)

\$\endgroup\$
1
  • \$\begingroup\$ Could you replace the Y-1 or 2 with 3-Y? \$\endgroup\$
    – Dadsdy
    Jun 10, 2023 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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