title: Create a checkerboard matrix

text:
# Question
Title: Create a checkerboard matrix
Take a positive integer **n** as input, and output a **n-by-n** checkerboard matrix consisting of **1** and **0**.

The top left digit should always be **1**.

**Test cases:**

```
n = 1
1

n = 2
1 0
0 1

n = 3
1 0 1
0 1 0
1 0 1

n = 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

```

Input and output formats are optional. Outputting the matrix as a list of lists is accepted.

# Answer
> 13 votes
# Jelly, 4 bytes

52 seconds!

```
+€ḶḂ

```

Try it online!

# Answer
> 9 votes
# MATL, 5 bytes

```
:otYT

```

Try it at **MATL online!**

### Explanation

Consider input `4` as an example.

```
:    % Implicit input, n. Push range [1 2 ... n]
     %   STACK: [1 2 3 4]
o    % Parity, element-wise
     %   STACK: [1 0 1 0]
t    % Duplicate
     %   STACK: [1 0 1 0], [1 0 1 0]
YT   % Toeplitz matrix with two inputs. Implicit display
     %   STACK: [1 0 1 0;
     %           0 1 0 1;
     %           1 0 1 0;
     5           0 1 0 1]

```

# Answer
> 7 votes
# Japt, 6 bytes

```
ÆÇ+X v

```

Test it online! (Uses `-Q` flag for easier visualisation)

### Explanation

```
 Æ   Ç   +X v
UoX{UoZ{Z+X v}}  // Ungolfed
                 // Implicit: U = input number
UoX{          }  // Create the range [0...U), and map each item X to
    UoZ{     }   //   create the range [0...U), and map each item Z to
        Z+X      //     Z + X
            v    //     is divisible by 2.
                 // Implicit: output result of last expression

```

An interesting thing to note is that `v` is *not* a "divisible by 2" built-in. Instead, it's a "divisible by X" built-in. However, unlike most golfing languages, Japt's functions do not have fixed arity (they can accept any number of right-arguments). When given 0 right-arguments, `v` assumes you wanted `2`, and so acts exactly like it was given `2` instead of nothing.

# Answer
> 7 votes
# , ~~16~~, 15 bytes

```
Ài10ÀñÙxñÎÀlD

```

Try it online!

Hexdump:

```
00000000: c069 3130 1bc0 adf1 d978 f1ce c06c 44    .i10.....x...lD

```

# Answer
> 7 votes
## Haskell, ~~50~~ ~~41~~ ~~39~~ 38 bytes

*Thanks to nimi and xnor for helping to shave off a total of ~~9~~ 10 bytes*

```
f n=r[r"10",r"01"]where r=take n.cycle

```

Alternately, for one byte more:

```
(!)=(.cycle).take
f n=n![n!"10",n!"01"]

```

or:

```
r=flip take.cycle
f n=r[r"10"n,r"01"n]n

```

Probably suboptimal, but a clean, straightforward approach.

# Answer
> 5 votes
# APL (Dyalog), 8 bytes

```
~2|⍳∘.+⍳

```

Try it online!

### Explanation

Let's call the argument `n`.

```
⍳∘.+⍳

```

This creates a matrix

```
1+1 1+2 1+2 .. 1+n
2+1 2+2 2+3 .. 2+n
...
n+1 n+2 n+3 .. n+n

```

Then `2|` takes modulo 2 of the matrix (it vectorises) after which `~` takes the NOT of the result.

# Answer
> 5 votes
## JavaScript ES6, ~~55~~ ~~54~~ ~~51~~ 46 bytes

*Saved 1 byte thanks to @Neil*

*Saved 2 bytes thanks to @Arnauld*

```
n=>[...Array(n)].map((_,i,a)=>a.map(_=>++i&1))

```

Try it online!

This outputs as an array of arrays. JavaScript ranges are pretty unweildy but I use `[...Array(n)]` which generates an array of size `n`

# Answer
> 4 votes
## Mathematica, 25 bytes

```
1-Plus~Array~{#,#}~Mod~2&

```

# Answer
> 4 votes
# Retina, ~~33~~ 30 bytes

```
.+
$*
1
$_¶
11
10
T`10`01`¶.+¶

```

Try it online! Explanation: The first stage converts the input to unary using `1`s (conveniently!) while the second stage turns the value into a square. The third stage inverts alternate bits on each row while the last stage inverts bits on alternate rows. Edit: Saved 3 bytes thanks to @MartinEnder.

# Answer
> 4 votes
# 05AB1E, ~~9~~ 7 bytes

-2 bytes thanks to Emigna

```
LDÈD_‚è

```

Try it online!

### Explanation

```
LDÈD_‚sè» Argument n
LD        Push list [1 .. n], duplicate
  ÈD      Map is_uneven, duplicate
    _     Negate boolean (0 -> 1, 1 -> 0)
     ‚    List of top two elements of stack
      è   For each i in [1 .. n], get element at i in above created list
          In 05AB1E the element at index 2 in [0, 1] is 0 again

```

# Answer
> 3 votes
# MATL, 7 bytes

```
:t!+2\~

```

Try it online!

**Explanation:**

```
         % Implicit input (n)
:        % Range from 1-n, [1,2,3]
 t       % Duplicate, [1,2,3], [1,2,3]
  !      % Transpose, [1,2,3], [1;2;3]
   +     % Add        [2,3,4; 3,4,5; 4,5,6]
    2    % Push 2     [2,3,4; 3,4,5; 4,5,6], 2
     \   % Modulus    [0,1,0; 1,0,1; 0,1,0]
      ~  % Negate     [1,0,1; 0,1,0; 1,0,1]

```

Note: I started solving this in MATL *after* I posted the challenge.

# Answer
> 3 votes
# Java (OpenJDK 8), ~~80~~ 77 bytes

-3 bytes thanks to Kevin Cruijssen

```
j->{String s="1";for(int i=1;i<j*j;s+=i++/j+i%j&1)s+=1>i%j?"\n":"";return s;}

```

Try it online!

Oh look, a semi-reasonable length java answer, with lots of fun operators.

lambda which takes an int and returns a String. Works by using the row number and column number using / and % to determine which value it should be, mod 2;

Ungolfed:

```
j->{
    String s="1";
    for(int i=1; i<j*j; s+= i++/j + i%j&1 )
        s+= 1>i%j ? "\n" : "";
    return s;
}

```

# Answer
> 3 votes
# Brachylog, 15 bytes

```
^₂⟦₁%₂ᵐ;?ḍ₎pᵐ.\

```

Try it online!

### Explanation

```
Example Input: 4

^₂               Square:                            16
  ⟦₁             1-indexed Range:                   [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
    %₂ᵐ          Map Mod 2:                         [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]
       ;?ḍ₎      Input-Chotomize:                   [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]]
           pᵐ.   Map permute such that..
             .\  ..the output is its own transpose: [[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]]

```

# Answer
> 3 votes
## Clojure, 36 bytes

```
#(take %(partition % 1(cycle[1 0])))

```

Yay, right tool for the job.

# Answer
> 3 votes
# , 9 bytes

```
<0&=$&1 0

```

Try it online!

# Answer
> 3 votes
# Nekomata, 5 bytes

```
ᵒ+→2%

```

Attempt This Online!

```
ᵒ+→2%
ᵒ+       Create an (input x input) matrix where the element at (i,j) is i+j
  →      Increment
   2%    Mod 2

```

# Answer
> 2 votes
# Brachylog, 19 bytes

```
⟦₁Rg;Rz{z{++₁%₂}ᵐ}ᵐ

```

Try it online!

# Answer
> 2 votes
# Charcoal, 8 bytes

```
ＵＯＮ10¶01

```

Try it online! Explanation: This roughly translates to the following verbose code (unfortunately the deverbosifier is currently appending an unnecessary separator):

```
Oblong(InputNumber(), "10\n01");

```

# Answer
> 2 votes
# C, ~~69~~ ~~67~~ 63 bytes

*Thanks to @Kevin Cruijssen for saving two bytes and @ceilingcat for saving four bytes!*

```
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j;)printf("%d",j--+i&1);}

```

Try it online!

# Answer
> 2 votes
# Pyth, 9 bytes

```
VQm%+hdN2

```

Try this!

another 9 byte solution:

```
mm%+hdk2Q

```

Try it!

# Answer
> 2 votes
# ///, 87 bytes + input

```
/V/\\\///D/VV//*/k#D#k/k#D&k/k&DVk/k\D/SD/#/r
DSkk/10DSk/1D&/V#rV#0r;VV0;VVV1;V\D/r/S/&[unary input in asterisks]

```

Try it online! (input for 4)

## Unary input in `1`s, 95 bytes + input

```
/V/\\\///D/VV//&1/k#&D&|D/#k/k#D&k/k&DVk/k\D/SD/#/r
DSkk/10DSk/1D&/V#rV#0r;VV0;VVV1;V\D/r/S/&&[unary input in ones]|

```

Try it online! (input for 8)

### How does this work?

* `V` and `D` are to golf `\/` and `//` respectively.
* `/*/k#/` and `/&1/k#&//&|//` separate the input into the equivalent of `'k#'*len(input())`
* `/#k//k#//&k/k&//\/k/k\//` move all the `k`s to the `/r/S/` block
* `S`s are just used to pad instances where `k`s come after `/`s so that they don't get moved elsewhere, and the `S`s are then removed
* `#`s are then turned into `r\n`s
* The string of `k`s is turned into an alternating `1010...` string
* The `r\n`s are turned into `1010...\n`s
* Every pair of `1010...\n1010\n` is turned into `1010...\01010...;\n`
* Either `0;` or `1;` are trimmed off (because the `01010...` string is too long by 1)

# Answer
> 2 votes
# Octave, 24 bytes

```
@(n)~mod((a=(1:n))+a',2)

```

Try it online!

---

Or the same length:

```
@(n)mod(toeplitz(1:n),2)

```

Try it online!

# Answer
> 2 votes
# Mathematica, 23 bytes

```
ToeplitzMatrix@#~Mod~2&

```

# Answer
> 2 votes
# , ~~38~~ 37 bytes

```
n=scan();(matrix(1:n,n,n,T)+1:n-1)%%2

```

Try it online!

-1 byte thanks to Giuseppe

Takes advantage of R's recycling rules, firstly when creating the matrix, and secondly when adding 0:(n-1) to that matrix.

# Answer
> 2 votes
## Swi-Prolog, 142 bytes.

```
t(0,1).
t(1,0).
r([],_).
r([H|T],H):-t(H,I),r(T,I).
f([],_,_).
f([H|T],N,B):-length(H,N),r(H,B),t(B,D),f(T,N,D).
c(N,C):-length(C,N),f(C,N,1).

```

Try online - http://swish.swi-prolog.org/p/BuabBPrw.pl

It outputs a nested list, so the rules say:

* `t()` is a toggle, it makes the 0 -\> 1 and 1 -\> 0.
* `r()` succeeds for an individual row, which is a recursive check down a row that it is alternate ones and zeros only.
* `f()` recursively checks all the rows, that they are the right length, that they are valid rows with `r()` and that each row starts with a differing 0/1.
* `c(N,C)` says that C is a valid checkerboard of size N if the number of rows (nested lists) is N, and the helper f succeeds.

Test Cases:

# Answer
> 2 votes
# Arturo, ~~39~~ 36 bytes

```
$[n][map..1n'x->map..1n'y->%x+y+1 2]

```

Try it

-3 thanks to alephalpha's simpler method

Prettified and rearranged for clarity:

```
$[n][                     ; a function taking an argument n
    map 1..n 'x ->        ; map over 1..n, assign current elt to x
        map 1..n 'y ->    ; map over 1..n again, assign current elt to y
            (x+y+1)%2     ; what it looks like
]                         ; end function

```

# Answer
> 2 votes
# Vyxal, 5 bytes

```
ʁ∷:v=

```

Try it Online!

*-3 thanks to @lyxal*
*-1 thanks to @emanresuA*

#### Explanation

```
ʁ∷:v=    implicit input
ʁ        range(input)
 ∷       mod 2
  :      duplicate
   v=    equals, vectorised over the top list
         (generates a nested list)

```

Old:

```
ɾ∷ẋ⁽†ẇ    implicit input
ɾ         range(1, input+1)
 ∷        mod 2
  ẋ       repeated input times
     ẇ    apply to every 2nd item:
   ⁽†     vectorised not

```

```
ʁ:∷:†$"$İ    implicit input
ʁ:           range, duplicate
  ∷:         mod 2, duplicate
    †        vectorised not
     $"      swap and pair
       $İ    swap and index in

```

# Answer
> 2 votes
# TI-Basic, ~~30~~ 29 bytes

```
identity(Ans→[A]
Fill(1,[A]
cumSum([A]
2fPart(.5(Ans+Ansᵀ+[A]

```

Takes input in `Ans`.
-1 byte thanks to MarcMush

# Answer
> 1 votes
# PHP, 56 bytes

Output as string

```
for(;$i<$argn**2;)echo++$i%2^$n&1,$i%$argn?"":"
".!++$n;

```

Try it online!

# PHP, 66 bytes

Output as 2 D array

```
for(;$i<$argn**2;$i%$argn?:++$n)$r[+$n][]=++$i%2^$n&1;print_r($r);

```

Try it online!

# Answer
> 1 votes
# QBIC, 19 bytes

```
[:|?[b|?(a+c+1)%2';

```

## Explanation

```
[:|         FOR a = 1 to b (b is read from cmd line)
?           PRINT - linsert a linebreak in the output
[b|         FOR c = 1 to b
?(a+c+1)%2  PRINT a=c=1 modulo 2 (giving us the 1's and 0's
';            PRINT is followed b a literal semi-colon, suppressing newlines and
              tabs. Printing numbers in QBasic adds one space automatically.

```

# Answer
> 1 votes
# CJam, 17 bytes

```
{_[__AAb*<_:!]*<}

```

Try it online!

Returns a list (TIO link has formatted output).

# Answer
> 1 votes
# Bash + rs, 42

```
eval echo \$[~{1..$1}+{1..$1}\&1]|rs $1 $1

```

Try it online.

# Answer
> 1 votes
# Cheddar, 38 bytes

```
n->(|>n).map(i->(|>n).map(j->i+j+1&1))

```

Try it online!

# Answer
> 1 votes
# Python, ~~73 63 62~~ 66 bytes

Saved 4 bytes thanks to officialaimm

```
r=range(input());print[''.join([`(x+y+1)%2`for x in r])for y in r]

```

# Answer
> 1 votes
# Mathematica, 28 bytes

```
Cos[+##/2Pi]^2&~Array~{#,#}&

```

Pure function taking a positive integer as input and returning a 2D array. Uses the periodic function cos²(πx/2) to generate the 1s and 0s.

For a little more fun, how about the 32-byte solution

```
Sign@Zeta[1-+##]^2&~Array~{#,#}&

```

which uses the locations of the trivial zeros of the Riemann zeta function.

# Answer
> 1 votes
# q/kdb+, ~~37~~ 16 bytes

**Solution:**

```
{x#x#'(1 0;0 1)}

```

**Example:**

```
q){x#x#'(1 0;0 1)}1
1
q){x#x#'(1 0;0 1)}2
1 0
0 1
q){x#x#'(1 0;0 1)}3
1 0 1
0 1 0
1 0 1
q){x#x#'(1 0;0 1)}4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

```

**Explanation:**

2nd version is *much* simpler, and thus shorter and faster (4x). Create a 2-item list containing 01... and 10... to the length of the input, then take 'x' number of items from this new list.

```
{              } / lambda function
      (1 0;0 1)  / 2-item list of (0;1) and (1;0)
   x#'           / take 'x' items from each list, if x=3 then (1 0 1;0 1 0)
 x#              / take 'x' items from *this* list

```

**Notes:**

I've re-written this twice during this edit, went from 37-\>25-\>24-\>16 bytes. Now it's a little more competitive.

**Edits:**

* -21 bytes with complete re-write...

# Answer
> 1 votes
# braingasm, 21 bytes

```
;$[$[>+o:<]p[>+<]10.]

```

Explanation:

```
;                       Read a number from stdin.
 $[                 ]   That many times...
   $[     ]               That many times...
     >+o:<                  Increase the next cell and print its value modulo 2.
           p[   ]       If the input was even...
             >+<          Increase the next cell once more.
                 10.    Print a newline.

```

# Answer
> 1 votes
## J, 41 bytes

I know there's a J answer at 9, but I'm pleased to get anything working, even if it's not a tacit programming best possible..

```
ch=:monad define
2|(2$y)$(1+i.y),(i.y)
)

```

It takes a number `y` and generates two lists of numbers `1,2,3,..y` and `0,1,2,3,..y-1` to make the offset first and second row, appends them into one long list, reshapes that into a y,y matrix (wrapping around when it runs out), and then does modulo 2 on all the elements to make them a 1 or 0.

```
   ch 1
1

   ch 2
1 0
0 1

   ch 3
1 0 1
0 1 0
1 0 1

   ch 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

   ch 5
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1

```

# Answer
> 1 votes
# Haskell, 43 bytes

```
h=1:0:h
l=h:(0:h):l
s x=take x$map(take x)l

```

Try it online!

This creates the infinite checkerboard matrix and saves it to `l`. Then our function `s` chops off a square.

# Answer
> 1 votes
# Husk, 6 bytes

```
´Ṫ=↑İ¬

```

Try it online!

# Answer
> 1 votes
# Thunno, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

```
RD2%D1_ZPsAH

```

Attempt This Online! or see it in a nicer format

#### Explanation

```
RD2%D1_ZPsAH  # Implicit input                Example: n=3
RD            # Duplicate range(input)        STACK: [0, 1, 2],  [0, 1, 2]
  2%D         # Duplicate ^ mod 2             STACK: [0, 1, 2],  [0, 1, 0],  [0, 1, 0]
     1_       # 1 - top copy of ^             STACK: [0, 1, 2],  [0, 1, 0],  [1, 0, 1]
       ZP     # Pair top two items            STACK: [0, 1, 2],  [[0, 1, 0], [1, 0, 1]]
         sAH  # 1-based modular indexing      STACK: [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
              # Implicit output

```

# Answer
> 1 votes
# Pyt, 7 bytes

```
ř2%Đɐ=Ɩ

```

Try it online!

```
ř                    implicit input; řangify
 2%                  modulo 2
   Đ                 Đuplicate
    ɐ=               for ɐll possible pairs, check for equality
      Ɩ              coerce booleans to integers; implicit print

```

Prints list of lists

# Answer
> 1 votes
# Pip `-S`, 8 bytes

```
%U$+GMCa

```

Other list-formatting flags such as `-l` and `-p` work too. Without a flag, the list of lists is printed without any separators (e.g. `1001` for input `2`), which seemed like stretching the permissive output format a bit too far.

Attempt This Online!

### Explanation

```
       a  ; Command-line argument
     MC   ; Map to a square coordinate grid of that size:
  $+G     ;   Sum the two coordinates
 U        ;   Increment
%         ;   Mod 2

```

# Answer
> 1 votes
# Go, 89 bytes

```
import."fmt"
func f(n int){
for i:=1;i<=n;i++{
for j:=i;j<i+n;j++{Print(j%2)}
Println()}}

```

Attempt This Online!

Prints a multi-line string.

#### Explanation

```
import ."fmt"               // Boilerplate
func f(n int) {             // Function f taking an integer n:
for i := 1; i <= n; i++ {   //  Loop through each i in [1..n]:
for j := i; j < i+n; j++ {  //   Loop through each j in [i..i+n]:
Print(j%2)}                 //    Print j mod 2 without a newline
Println()}}                 //   Print a newline

```

# Answer
> 1 votes
# Thunno 2, 5 bytes

```
RɗDȷ=

```

Attempt This Online!

Port of my Vyxal answer.

#### Explanation

```
       # implicit input
R      # one range
 ɗ     # mod 2
  D    # duplicate
   ȷ   # outer product:
    =  #  equality
       # implicit output

```

# Answer
> 1 votes
# Uiua, 6 bytes

```
⊞=.◿2⇡

```

Try it!

```
⊞=.◿2⇡
     ⇡  # range
   ◿2   # modulo 2
  .     # duplicate
⊞=      # table by equality

```

# Answer
> 0 votes
# Mathematica, 28 bytes

```
Table[Mod[i+j+1,2],{i,#},{j,#}]&

```

# Answer
> 0 votes
## Julia, 38 bytes

```
n->map(x->x%2,(1:n).+transpose(0:n-1))

```

The usual approach

# Answer
> 0 votes
# Python 2, ~~72~~ ~~70~~ ~~61~~ 54 bytes

*-7 bytes thanks to Leaky Nun. -1 byte thanks to Wheat Wizard.*

```
lambda n:[[i-~j&1for i in range(n)]for j in range(n)]

```

Try it online!

# Answer
> 0 votes
# Actually, 15 bytes

```
r;╗⌠╜+u⌠2@%⌡M⌡M

```

Try it online!

# Answer
> 0 votes
# Python, 43 bytes

```
lambda n:[('10'*n)[i:i+n]for i in range(n)]

```

Try it online!

Anonymous function that outputs a list like `['1010', '0101', '1010', '0101']`.

# Answer
> 0 votes
# tcl, 82

```
time {set a "";time {set a $a[expr [incr i]%2]} $n;puts $a;if \!($n%2) incr\ i} $n

```

# demo

Still a looser, but I think i can be golfed down a little bit further.

# Answer
> 0 votes
**C#, 145 Bytes**

```
int u=1;int n=int.Parse(b.Text);for(int i=0;i<n;i++){if(i%2==0){u=1;}else{u=0;}for(int j=0;j<n;j++){t.Text+=u.ToString();u=1-u;}t.Text+="\r\n";}[enter link description here][1]

```

Try it online!

# Answer
> 0 votes
# Bash & coreutils, 82 bytes

```
x=$1;yes 10|tr -d \\n|dd bs=1 count=$[x*x*2]|fold -w$[x*2-1]|grep -om$x "^.\{$x\}"

```

Takes one command-line integer as input. Apparently the spaces between are optional.

# Answer
> 0 votes
# Common Lisp, SBCL, 81 bytes

version 1:

```
(#1=dotimes(i(set'a(read)))(#1#(j a)(format t"~:[1~;0~] "(oddp(+ j i))))(terpri))

```

version 2:

```
(lambda(n)(#1=dotimes(i n)(#1#(j n)(format t"~:[1~;0~] "(oddp(+ j i))))(terpri)))

```

Two loops, and inside I print either 1 and space or zero and space based on parity of `(+ j i)`. `(terpri)` for newline.

It's long, I know:/

# Answer
> 0 votes
# C# (.NET Core), 88 bytes

```
n=>{var r=new int[n,n];for(int i=0,j;i<n;i++)for(j=0;j<n;j++)r[i,j]=(i+j+1)%2;return r;}

```

Try it online!

I can't believe this is the shortest way to initialize a 2D array of integers, there must be another way...

# Answer
> 0 votes
# Perl 5, 49 bytes

```
$_=10x(($n=<>)/2).1x($n%2);say&&y/01/10/while$n--

```

Try it online!

# Answer
> 0 votes
# C (gcc), ~~60~~ 59 bytes

```
i;f(n){for(i=n*n;i--;)printf(i%n?"%d":"%d\n",i%n+i/n+1&1);}

```

Try it online!

# Answer
> 0 votes
# Japt `-m`, ~~5~~ 4 bytes

Outputs a 2D array.

```
W£°v

```

Try it

---
Tags: code-golf, number, matrix
---


title: Measure the lengths of binary patterns

text:
# Question
Title: Measure the lengths of binary patterns
Let's consider the sequence of the binary representation of positive integers (without any leading zero):

```
1 2  3  4   5   6   7   8    9    10   11   12   ...
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 ...

```

If we join them together, we get:

```
1101110010111011110001001101010111100 ...

```

If we now look for the patterns `/1+0+/`, we can split it as follows:

```
110 11100 10 1110 1111000 100 110 10 10 111100 ...

```

We define \\$s\_n\\$ as the length of the \\$n\\$-th pattern built that way. Your task is to generate this sequence.

The first few terms are:

```
3, 5, 2, 4, 7, 3, 3, 2, 2, 6, 3, 5, 9, 4, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 8, 4, 4, 2, 3, 7, 4, 6, 11, 5, 5, ...

```

Related OEIS sequence: A056062, which includes the binary representation of \\$0\\$ in the initial string and counts \\$0\\$'s and \\$1\\$'s separately.

## Rules

You may either:

* take \\$n\\$ as input and return the \\$n\\$-th term, 1-indexed
* take \\$n\\$ as input and return the \\$n\\$-th term, 0-indexed
* take \\$n\\$ as input and return the \\$n\\$ first terms
* take no input and print the sequence forever

This is a challenge.

## Some more examples

The following terms are 1-indexed.

```
s(81)    = 13
s(100)   = 3
s(101)   = 2
s(200)   = 5
s(1000)  = 5
s(1025)  = 19
s(53249) = 29

```

# Answer
# Husk, 7 bytes

```
mLġ≤ṁḋN

```

Try it online!

Takes no input and prints ALL the numbers!

### Explanation

```
mLġ≤ṁḋN
      N        The list of all positive integers [1,2,3...]
    ṁḋ         Convert each to binary and concatenate the resulting digits
  ġ≤           Split them in groups where each digit is less than or equal to the previous one (basically cuts wherever there is a 0 followed by a 1)
mL             Compute the length of each group

```
> 9 votes

# Answer
# Python, ~~77~~ 67 bytes

```
lambda n:len(''.join(f'{i:b}'for i in range(9*n)).split('01')[n])+2

```

Try it online!

Returns the \\$n^\text{th}\\$ term, 1-indexed.
> 5 votes

# Answer
# MATL, 15 bytes

```
E:"@B]v&Y'2esG)

```

This takes `n` as input and outputs the `n`-th term, 1-indexed.

Try it online!

### Explanation

A binary pattern of the specified form ends at least as often as every even number. So for input `n`, considering the numbers `1`, `2`, ..., `2*n` guarantees that at least `n` patterns are obtained.

```
E      % Implicit input: n. Push 2*n
:"     % For each k in [| 2 ... 2*n]
  @    %   Push k
  B    %   Binary expansion. Gives a row vector containing 1's and 0's
]      % End
v      % Concatenate everything into a column vector
&Y'    % Lengths of run-length encoding. Runs contain 1's and 0's alternately
2e     % Reshape as a two-column matrix, in column-major order
s      % Sum of each column. This gives the lenghts of the desired patterns
G)     % Take the n-th entry. Implicit display

```
> 4 votes

# Answer
# Haskell, 80 bytes

```
([1..]>>=f)#0
f 0=[]
f x=f(div x 2)++[mod x 2]
(0:1:x)#l=l+1:x#1
(a:x)#l=x#(l+1)

```

Try it online!

Inspired by Leo's Husk answer, calculates an infinite list.
> 4 votes

# Answer
# Octave, 62 bytes

```
@(n)diff(regexp([arrayfun(@dec2bin,1:4*n,'un',0){:}],'1+'))(n)

```

Try it online!

### Explanation

```
@(n)                                                           % function with input n
                                   1:4*n                       % range [1, 2, ... 4*n]
                 arrayfun(@dec2bin,     ,'un',0)               % convert each to binary string
                [                               {:}]           % concat into one string
         regexp(                                    ,'1+')     % starting indices of runs of 1's
    diff(                                                 )    % consecutive differences
                                                           (n) % take n-th entry

```
> 4 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
ḤB€FI»0kƲẈḣ

```

Try it online!

A monadic link taking an integer \\$n\\$ and returning the first \\$n\\$ terms of the series.

Change from `×9` to  inspired by @JonathanAllan’s answer. Thanks!
> 2 votes

# Answer
# Jelly, 11 bytes

```
ḤB€FŒgẈ+2/ḣ

```

A monadic Link accepting an integer, `n`, which yields a list of the first `n` values.

**Try it online!**

### How?

```
ḤB€FŒgẈ+2/ḣ - Link: integer, n
Ḥ           - double (n)
  €         - for each v in (implicit range = [1..2n]):
 B          -   (v) to binary
   F        - flatten
    Œg      - group runs
      Ẉ     - get lengths
        2/  - 2-wise reduce by:
       +    -   addition
          ḣ - head to index (n)

```
> 2 votes

# Answer
# Haskell, ~~135~~ 128 bytes

* Saved seven bytes thanks to ovs.

```
g$b=<<[1..]
b 0=[];b n=b(div n 2)++[mod n 2]
l(1:r)1=1+l r 1;l(0:r)0=1+l r 0;l(0:r)1=1+l r 0;l(1:r)0=0
g a=l a 1:g(drop(l a 1)a)

```

Try it online!
> 2 votes

# Answer
# bash + GNU utilities, ~~76~~ ~~58~~ 57 bytes

```
seq -f 2o%.fn $[2*$1]|dc|sed -E "s/(1*0*){$1}.*/\1Zp/"|dc

```

Try it online!

*Thanks to user41805 for suggestions that ended up shaving 18 bytes off! And for 1 more byte now too.*

Takes \\$n\\$ as an argument, and prints the \\$n^\text{th}\\$ entry in the sequence (with 1-based indexing).
> 2 votes

# Answer
# Perl 5 -n, 73 bytes

```
$_=join'',map{sprintf"%b",$_}1..($n=$_)*2;say y///c for(/1+0+/g)[0..$n-1]

```

Try it online!

Takes input `n` via stdin, prints the first `n` numbers in the sequence.
> 2 votes

# Answer
# 05AB1E, 9 bytes

```
∞bSγ2ôεSg

```

~~Untested, since TIO isn't working.. \>.\> But it should work (unless one of those builtins used isn't lazy).
I'll try to finally install 05AB1E locally later today to verify if it indeed works.~~
EDIT: Installed 05AB1E locally, and apparently it didn't work due to the `J`oin on the infinite list. So here an alternative 9-byter that does actually work.

Outputs the infinite sequence.

Try it online.

**Explanation:**

```
∞          # Push an infinite list of positive integers: [1,2,3,4,5,6,...]
 b         # Convert each to a binary string
           #  → ["1","10","11","100","101","110",...]
  S        # Convert it to a flattened list of digits
           #  → [1,1,0,1,1,1,0,0,1,0,1,1,1,0,...]
   γ       # Split them into parts of consecutive equal digits
           #  → [[1,1],[0],[1,1,1],[0,0],[1],[0],[1,1,1],[0],...]
    2ô     # Split all that into parts of size 2
           #  → [[[1,1],[0]],[[1,1,1],[0,0]],[[1],[0]],[[1,1,1],[0]],...]
      ε    # Map over each pair
       S   #  Convert it to a flattened list of digits again
           #   → [[1,1,0],[1,1,1,0,0],[1,0],[1,1,1,0],...]
        g  #  Pop and push its length
           #   → [3,5,2,4,...]
           # (after which the mapped infinite list is output implicitly as result)

```
> 2 votes

# Answer
# Ruby, 48 bytes

```
->n{("%b%b"*n%[*1..n*2]).scan(/1+0+/)[n-1].size}

```

Try it online!
> 2 votes

# Answer
# K (ngn/k), 26 bytes

```
{x##'(&0>':t)_t:,/2\'!2*x}

```

Try it online!

Returns the first `n` items.

# , 35 bytes

```
{[:((1,2</\])#;.1])@;[:#:&.>[:i.3&*

```

Try it online!

Returns the `n`th item
> 2 votes

# Answer
# Charcoal, ~~34~~ 22 bytes

```
≔…⌕Ａ⭆⊗⊕θ⍘ι²01⊕θηＩ⁻⊟η⊟η

```

Try it online! Link is to verbose version of code. Based on @LuisMendo's observation that the numbers up to `2n` provide sufficient digits, although I search for `01` so I actually need `0` through `2n+1`. Explanation:

```
⭆⊗⊕θ⍘ι²

```

Convert all the numbers from `0` to `2n+1` to base 2 and concatenate them.

```
≔…⌕Ａ...01⊕θη

```

Find the positions of the substrings `01` but truncated after the `n`th entry.

```
Ｉ⁻⊟η⊟η

```

Output the difference between the last two positions.
> 1 votes

# Answer
# Jelly, ~~15~~ 14 bytes

```
×3ŻBFœṣØ.ḊẈ+2ḣ

```

Try it online! Thanks to @JonathanAllan and @NickKennedy for helping me out, in chat, to finish this solution. I came up with `×3RBFœṣØ.Ẉ+2ḣ` but that fails for `n = 1`!

**How it works**:

```
×3ŻBFœṣØ.ḊẈ+2ḣ    Monadic link: takes `n` as input and returns the first `n` terms
×3                Multiply input by three and
  Ż                create the list [0, 1, ..., 3n].
   B              Get the binary representation of each number and
    F              flatten to get [0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, ...]
                  Now we find the /1+0+/ patterns by looking at occurrences of [0, 1],
                   i.e. when one pattern ends and the next begins:
     œṣ           Split the [0, 1, 1, 0, 1, 1, 1, 0 ...] list at occurrences of
       Ø.         [0, 1], so [0, 1, 1, 0, 1, 1, 1, 0 ...] -> [[], [1], [1, 1, ...], ...]
         Ḋ         and drop the first element of the resulting list (the empty one).
          Ẉ       Finally we get the length of each sublist,
           +2      add 2 (to compensate for the lost 1 and 0),
             ḣ     and take the first `n` elements of that.

```
> 1 votes

# Answer
# Japt, 11 bytes

Outputs the `n`th 1-indexed term.

```
g°U²ô¤¬ò<)l

```

Try it

```
g°U²ô¤¬ò<)l     :Implicit input of integer U
g               :Index into
 °U             :  Increment U
   ²            :  Square it
    ô           :  Range [0,result]
     ¤          :  To binary strings
      ¬         :  Join
       ò<       :  Partition after characters that are less than the next
         )      :End indexing
          l     :Length

```
> 1 votes

# Answer
# Red, ~~122~~ 111 bytes

```
func[n][b: copy""repeat i 2 * n[append b find enbase/base
to#{}i 2"1"]parse b[n copy i[any"1"any"0"]]length? i]

```

Try it online!
> 1 votes

# Answer
# PHP, 108 bytes

```
for($a=[$p=$i=1];;$p=$c,$o++){if(!$a)$a=str_split(decbin(++$i));if($p<$c=array_shift($a)){echo$o,',';$o=0;}}

```

Try it online!

Will print the sequence indefinitely.
> 1 votes

# Answer
# C (gcc), ~~124~~ \\$\cdots\\$ ~~109~~ 104 bytes

Saved ~~2~~ ~~3~~ ~~4~~ ~~8~~ ~~9~~ 14 bytes thanks to Arnauld!!!

```
c;t;b;i;f(n){for(i=c=0,t=1;++i;){for(b=0;i>>++b;);for(;b--;++c)if(t^i>>b&1&&(t^=1)?c*=!--n:0)return c;}}

```

Try it online!

Goes through positive integers \\$i\\$ catching transitions from \\$0\\$ to \\$1\\$ as it rolls through the non-leading-zero bits of the \\$i\\$'s.

Returns the \\$n^\text{th}\\$ term, 1-indexed.
> 1 votes

# Answer
# Gaia, 13 bytes

```
ḣ┅b¦_ėt(2/Σ¦E

```

Try it online!

Port of Luis' MATL answer.
> 1 votes

# Answer
# `x`, 7 bytes

REALLY slow. The array is 1-indexed and it outputs all upto the input. (Glad that I tie with Husk BTW. Special bonus: it doesn't involve infinite lists!)

```
♫│x╤►U╟

```

Uncompressed:

```
^k2BLHkr

```

# Explanation

```
^        % 10 ^ input. Make sure that enough items are calculated.
 k       % Find the length range of that.
  2B     % Convert every item to binary.
         % Since at least 1 item >= the base, this vectorizes.

         % Automatic flatten before grouping
    LH   % Grouping: Is the previous item >= current item?
      kr % Reduce by length

Flag:x  % Output all items upto the input, including input-indexed item. 1-indexed.

```

# `x`, 8 bytes

You can try this without having to wait for a long time.

```
☺│╪å∟↕c╟

```

Uncompressed:

```
3*k2BLHkr

```

# Explanation

3*         % Input times 3, idea copied from RGS's answer.
  k        % Provide a length-range
   2B      % Convert all to binary
     LH    % Group by >=
           % Automatic flattening before grouping
       kr  % Reduce by length

Flag:x      % Output all less than the input index. INCLUDING the input index item.
```
</code></pre>
> 1 votes

# Answer
# APL (Dyalog Extended), 17 bytes

```
{⍵⊃≢¨⊆⍨1+∊⊤¨⍳+⍨⍵}

```

Try it online!

Gives nth term, 1-indexed.

### How it works

```
{⍵⊃≢¨⊆⍨1+∊⊤¨⍳+⍨⍵}
{               }  ⍝ ⍵←n
             +⍨⍵   ⍝ Double of n
            ⍳      ⍝ 1 .. 2n, inclusive
         ∊⊤¨  ⍝ Convert each to binary and flatten
       1+     ⍝ Add 1
     ⊆⍨       ⍝ Partition self into non-increasing segments
              ⍝ (Without 1+, zero items are dropped)
   ≢¨  ⍝ Lengths of each segment
 ⍵⊃    ⍝ Take nth item

```
> 1 votes

# Answer
# Vyxal, 67 bits<sup>v2</sup>, 8.375 bytes

```
Þ∞bfĠ2ẇvf@

```

Try it Online!

Bitstring:

```
0010011101110110001111101100111001011111001011101000111011000011110

```
> 1 votes

# Answer
# Factor, 92 bytes

```
: f ( n -- n ) dup 3 * [0,b] [ >bin ] map concat "01" " " replace " " split nth length 2 + ;

```

Try it online!
> 0 votes

# Answer
# APL (Dyalog Classic), 29 bytes

```
{⍵+.=+\2</∊,(2∘⊥⍣¯1)¨⍳3+⍵}

```

Try it online!

*Will post explanation soon!*
> 0 votes

# Answer
# Zpr'(h, 369 bytes

```
s |> \

```

```
(g (foldr (op-> ++) () (map b |N)))
(e ())|>o
(e (S ()))|>z
(e (S (S .n)))|>(e n)
(h ())|>()
(h (S ()))|>()
(h (S (S .n)))|>(S (h n))
(b ())|>()
(b (S .n))|>((b (h (S n))) ++ (' (e n) ()))
(l (' z (' o .r)))|>1
(l (' z (' z .r)))|>(S (l (' z r)))
(l (' o (' o .r)))|>(S (l (' o r)))
(l (' o (' z .r)))|>(S (l (' z r)))
(g .a)|>(' (l a) (g (drop (l a) a)))
<|prelude.zpr

```

```
main |> (take 8 s)

```

# Execution

```
Zpr-h-master/stdlib$ ../Zprh --de-peano above.zpr
(' 3 (' 5 (' 2 (' 4 (' 7 (' 3 (' 3 (' 2 0))))))))

```

# Explanation

```
; build the sequence by splitting the bits of all natural numbers |N
sequence |> (generate (foldr (op-> ++) () (map bits |N)))

; compute if a natural number is even (parity shifted by one)
(even ())         |> one
(even (S ()))     |> zero
(even (S (S .n))) |> (even n)

; halve a natural number, rounding down
(halve ())         |> ()
(halve (S ()))     |> ()
(halve (S (S .n))) |> (S (halve n))

; compute a natural number's binary representation
(bits ())     |> ()
(bits (S .n)) |> ((bits (halve (S n))) ++ (' (even n) ()))

; compute the length of the pattern sought after at the bit stream's beginning
(len (' zero (' one .rest)))  |> 1
(len (' zero (' zero .rest))) |> (S (len (' zero rest)))
(len (' one (' one .rest)))   |> (S (len (' one rest)))
(len (' one (' zero .rest)))  |> (S (len (' zero rest)))

(generate .all-bits) |> (' (len all-bits) \
                           (generate (drop (len all-bits) all-bits)))

; include from the standard library
<| prelude.zpr

; output the first eight sequence members
main |> (take 8 sequence)

```
> 0 votes

# Answer
# Wolfram Language (Mathematica), 70 bytes

```
Tr[1^Join@@Partition[Split[Join@@IntegerDigits[Range[2#],2]],2][[#]]]&

```

Try it online!
> 0 votes

---
Tags: code-golf, sequence, binary
---


title: Numbers Increase While Letters Decrease

text:
# Question
Title: Numbers Increase While Letters Decrease
Inspired by this Stack Overflow question: Sorting a list: numbers in ascending, letters in descending. Your task is to solve the following problem and, as this is , you should do so in as few as bytes as possible.

You should take a list of objects as input containing letters (any reasonable form: `string`, `char`, etc) and numbers. You should then sort the numbers into ascending order and the letters into descending order. However, you should keep letters in letter positions and numbers in number positions. For example, if the list is:

```
[L, D, L, L, D, L]

```

The output list should be in the form of:

```
[L, D, L, L, D, L]

```

**Workthrough**

Input: `['a', 2, 'b', 1, 'c', 3]`

* Sort the numbers into ascending order: `[1, 2, 3]`
* Sort the letters into descending order: `['c', 'b', 'a']`
* Join them back but keep the order the same: `['c', 1', 'b', 2, 'a', 3]`

**Rules**

* The list will only contain letters and digits.
* The list may be empty.
* The list may only contain letters or only digits.
* **If** your language does not support mixed type arrays you may use digit characters instead of numbers. Note that if your language does support this you must use mixed types.
* Letters will only be `[a-z]` or `[A-Z]`, you may choose which one.
* Letters are sorted as `a` being lowest, `z` being highest i.e. `a = 1, z = 26`.
* Standard loopholes are forbidden.
* I/O may be by any standard means including as a string.

**Test cases**

```
[5, 'a', 'x', 3, 6, 'b'] -> [3, 'x', 'b', 5, 6, 'a']

[ 3, 2, 1] -> [ 1, 2, 3 ]

[ 'a', 'b', 'c' ] -> [ 'c', 'b', 'a' ]

[] -> []

[ 2, 3, 2, 1 ] -> [1, 2, 2, 3]

```

As this is the shortest answer in bytes wins!

# Answer
# Retina, 10 bytes

```
O`\d
O^`\D

```

Try it online!

The `O` stage in Retina can directly perform the kind of selective sorting required by this challenge.

Here the first line sorts digits while the second line sorts non-digits in reverse.
> 9 votes

# Answer
# Python 2, ~~53~~ ~~52~~ 51 bytes

-2 bytes thanks to g.rocket
-1 byte thanks to Jonathan Frech
-1 byte thanks to RootTwo

```
def F(x):n=sorted(x);print[n.pop(-(e>x))for e in x]

```

Try it online!

The `sorted` list will have the numbers first and then the chars like `[3, 5, 6, 'a', 'b', 'x']`, then use `e>x` to filter what is number and what is char, in python any number is less than a list (input) and a list is less than a string.
> 14 votes

# Answer
# APL (Dyalog), ~~27~~ 26 bytes

Expects characters to be uppercase

```
(⍋⊃¨⊂)@(~e)(⍒⊃¨⊂)@(e←∊∘⎕A)

```

Try it online!

This is just two applications of the form `f@g`, apply the function `f` on the items indicated by `g`.

For the first application we use:
`f`: `⍒⊃¨⊂` the descending grades () each pick (`⊃¨`) from the entire argument ().
`g`: `(e←∊∘⎕A)` members () of () the **A**lphabet (`⎕A`), and store () this function as `e`.

For the second application we use:
`f`: `⍋⊃¨⊂` the ascending grades () each pick (`⊃¨`) from the entire argument ().
`g`: `(~e)` not (`~`) members of the alphabet (`e`; the function we stored before)
> 9 votes

# Answer
## JavaScript (ES6), ~~71~~ ~~51~~ 47 bytes

*Saved 20 bytes by just using `sort()`, as suggested by @JustinMariner*
*Saved 4 more bytes thanks to @CraigAyre*

Using a similar approach as Rod's Python answer:

```
a=>[...a].map(n=>a.sort()[1/n?'shift':'pop']())

```

### Test cases

```
let f =

a=>[...a].map(n=>a.sort()[1/n?'shift':'pop']())

console.log(JSON.stringify(f(['a', 2, 'b', 1, 'c', 3]))) // -> ['c', 1', 'b', 2, 'a', 3]
console.log(JSON.stringify(f([5, 'a', 'x', 3, 6, 'b']))) // -> [3, 'x', 'b', 5, 6, 'a']
console.log(JSON.stringify(f([3, 2, 1]))) // -> [ 1, 2, 3 ]
console.log(JSON.stringify(f(['a', 'b', 'c']))) // -> [ 'c', 'b', 'a' ]
console.log(JSON.stringify(f([]))) // -> []
console.log(JSON.stringify(f([2, 3, 2, 1]))) // -> [1, 2, 2, 3]
```
> 9 votes

# Answer
# , ~~83~~ 76 bytes

*-7 bytes thanks to Miff*

```
function(n){u=unlist
d=n%in%0:9
n[d]=sort(u(n[d]))
n[!d]=sort(u(n[!d]),T)
n}

```

This is the same as the below, but it allows for mixed-type input as a `list` rather than an `atomic` vector (which would typecast everything as characters with mixed types).

Try it online!

# , ~~68~~ 61 bytes

*-7 bytes thanks to Miff*

```
function(n){d=n%in%0:9
n[d]=sort(n[d])
n[!d]=sort(n[!d],T)
n}

```

Anonymous function. All digits are cast to characters in this case. `n[-d]` is the array without the digits. Returns `NULL` (empty list) on empty input.

Try it online!
> 5 votes

# Answer
# Japt, ~~18~~ 15 bytes

*Thanks @Shaggy for -3 bytes and for help fixing for arrays with `0`s.*

```

c ñc
®¤?Vv :Vo

```

First line is intentionally left blank.

Try it online! using `-Q` to view the formatted array.

## Explanation

First line is blank to avoid overwriting the input array.
`[5, 'a', 'x', 3, 6, 'b']`

```
c ñc

```

Make a copy by flattening (`c`) the input array, then sort (`ñ`) with strings represented by their char code (`c`). This is stored in `V`.
`[3, 5, 6, 'a', 'b', 'x']`

```
£

```

Then map the input array by the function...

```
¤?Vv :Vo

```

Turn numbers into binary strings (truthy) or strings into `""` (falsy) (`¤`). If truthy, remove from the start of `V` (`v`), otherwise remove from the end (`o`).
> 4 votes

# Answer
# JavaScript, ~~164~~ ~~162~~ ~~158~~ 142 bytes

edit 1: 2 bytes less after removing a redundant assignment of v.

edit 2: 4 bytes less thanks to TheLethalCoder.

edit 3: 16 bytes less thanks to brilliant hints from Justin Mariner

```
x=>eval("n=v=>typeof(v)=='number';l=x.length;for(i=0;i<l;x[i++]=x[m],x[m]=w){for(v=w=x[j=m=i];++j<l;)n(e=x[j])==n(w)&&e<v==n(w)&&(m=j,v=e)}x")

```

It's my very first time in code-golf, so it can surely be improved... But still, worth a try.

The program performs a variant of selection sort, which only takes into account the values of the same type as the current one (swapping only a number and a number, or a letter and a letter)

Readable form:

```
x=>eval("
    n=v=>typeof(v)=='number';
    l=x.length;
    for(i=0;i<l;x[i++]=x[m],x[m]=w){
        for(v=w=x[j=m=i];++j<l;)
            n(e=x[j])==n(w) && e<v==n(w) && (m=j,v=e)
    }
    x
")

```
> 4 votes

# Answer
# Jelly, 9 bytes

```
OÞḢṪOƑ}?Ɱ

```

Try it online!

Takes input as a flat array (Jelly typically treats strings as char arrays, so `[5, 'a', 'x', 3, 6, 'b'] -> [5, ['a'], ['x'], 3, 6, ['b']]`. The Footer flattens this array for you).

Similar to PurkkaKoodari's Jelly answer

## How it works

```
OÞḢṪOƑ}?Ɱ - Main link. Takes an array A on the left
 Þ        - Sort by:
O         -   Ordinal
            This shuffles the strings to the end,
             sorting both the strings and the numbers
        Ɱ - Over each element E in A:
       ?  -   If statement:
    OƑ}   -     Condition: E is a number?
  Ḣ       -     Then: Pop and yield the first element of A sorted
   Ṫ      -     Else: Pop and yield the last element of A sorted

```
> 4 votes

# Answer
# Jelly, 14 bytes

```
FOÞɓṪ}Ḣ}ẇØa$?€

```

Try it online!

Basically a port of Rod's Python solution.
> 3 votes

# Answer
# q/kdb+, ~~54~~ 53 bytes

**Solution:**

```
{x[w,q]:asc[x w:(&)d],desc x q:(&)(~)d:-7=type@/:x;x}

```

**Examples:**

```
q){x[w,q]:asc[x w:(&)d],desc x q:(&)(~)d:-7=type@/:x;x}(5;"a";"x";3;6;"b") / mixed list
3
"x"
"b"
5
6
"a"
q){x[w,q]:asc[x w:(&)d],desc x q:(&)(~)d:-7=type@/:x;x}3 2 1   / simple list
1 2 3
q){x[w,q]:asc[x w:(&)d],desc x q:(&)(~)d:-7=type@/:x;x}"abc"   / simple list
"cba"
q){x[w,q]:asc[x w:(&)d],desc x q:(&)(~)d:-7=type@/:x;x}2 3 2 1 / simple list
1 2 2 3

```

**Explanation:**

Find the chars in the list, sort descending, find the longs in the list, sort them ascending, join to get a list of, e.g. `("x";"b";"a";3;5;6)`, then assign the sorted values back to their original positions in the list, e.g. at `0 3 4 1 2 5`.

Golfing is just switching out q keywords (`each`, `where` and `not`) for their `k` equivalent (which requires them to be wrapped in brackets).

```
{x[w,q]:asc[x w:where d],desc x q:where not d:-7=type each x;x} / ungolfed
{                                                           ; } / lambda function with 2 statements
                                                 type each x    / return types of elements in mixed list
                                              -7=               / true where item is a long
                                            d:                  / save this bool array in d
                                        not                     / invert
                                  where                         / indices where true (we have chars)
                                q:                              / save these indices in q
                              x                                 / values of x at these indices
                         desc                                   / sort them descending
                        ,                                       / join/contatenate
                where d                                         / indices where we have digits
              w:                                                / save this in w
            x                                                   / values of x at these indices
        asc[           ]                                        / sort them ascending
 x[w,q]:                                                        / assign this list to x at indices w,q
                                                             x  / return x

```

**Edits**

* -1 byte as don't need square brackets around `desc`
> 3 votes

# Answer
# C++17 (gcc), 219 bytes

```
#include <variant>
#include <set>
using V=std::variant<char,int>;void f(V*a,V*b){std::set<V>S[2];for(V*c=a;c<b;++c)S[c->index()].insert(*c);auto
C=S->rbegin();auto N=S[1].begin();for(;a<b;++a)*a=(a->index()?*N++:*C++);}

```

Try it online!

Hardly competitive. But I must support mixed-type arrays? FINE.

Accepts an array of variants in range style, and modifies it in place. Copies the input into two sorted sets, and then back into the input/output array.
> 3 votes

# Answer
# Japt, 9 bytes

I *knew* there had to be a (golfy) way to do this without any sort of conditional :)

Outputs an array of singleton arrays. Replace `£` with `c@` to output a flat array.

```
£=ñs)jÓXÌ

```

Try it

```
£=ñs)jÓXÎ     :Implicit input of array U
£             :Map each X (or flat map with c@)
 =            :  Reassign to U
  ñ           :    Sort by
   s          :      Converting to string if an integer, slicing if a string (which does nothing to the string if given no arguments)
    )         :  End reassignment
     j        :  Remove (mutating the original) and return the element at modular 0-based index
      Ó       :    Bitwise NOT of the negation of (i.e, decrement)
       XÎ     :    Sign of difference of X with -1 if an integer, last character if a string (resulting in 0 if an integer or -1 if a string)

```
> 3 votes

# Answer
# Python, ~~145~~ ~~139~~ 130 bytes

*6 bytes saved thanks to @officialaimm*

*9 bytes saved thanks to @Chris\_Rands*

```
g=lambda s,a:sorted(x for x in s if(type(x)==str)==a)
def f(s):l,n=g(s,1),g(s,0)[::-1];return[[n,l][type(x)==str].pop()for x in s]

```

Try it online!
> 2 votes

# Answer
# Mathematica, 203 bytes

```
(K=Reverse;B=Complement;L=Length;S=Position[#,_Integer];T=Sort@Cases[#,_Integer];G=K@B[#,T];V=B[Range@L@#,Flatten@S];R=K@Sort@#;Table[R[[Min@S[[i]]]]=T[[i]],{i,L@T}];Table[R[[V[[i]]]]=G[[i]],{i,L@G}];R)&

```

Try it online!
> 2 votes

# Answer
# Pyth, ~~12~~ 11 bytes

```
KSQm.(Kt>\@

```

**Try it online! or Try the Test Suite.**

---

# Explanation

```
KSQm.(Kt<d\@  - Full program with implicit input.

KSQ           - Assign a variable K to the lexicographically sorted input.
   m          - Map over the input (with a variable d).
    .(K       - Pop the sorted list at this location:
       >\@    - If d is lexicographically lower than '@', at 0 (the first element). Else, at -1 (the last element).

```
> 2 votes

# Answer
# C (gcc), 125 113 110 bytes

```
main(i){char*b,*c,s[99];for(gets(c=b=s);*++c||*(c=++b);)i=*b&64,i^*c&64||*c>*b^!i&&(i=*c,*c=*b,*b=i);puts(s);}

```

Try it online!

**Explained:**

```
main(i)
{
    char*b,*c,s[99];

    // slightly modified stupid bubblesort, this line in fact
    // does nested looping with a single for statement
    for(gets(c=b=s);*++c||*(c=++b);)
    // (undefined behavior here, there's no sequence point between accesses to c,
    // so this could go wrong. Works with the gcc version on tio.)

        // determine whether the current b is a letter:
        i=*b&64,

        // for doing anything, b and c must be the same "type":
        i^*c&64

            // when c > b for letter or c <= b for digit
            || *c>*b^!i

            // then swap
            && (i=*c,*c=*b,*b=i);

    puts(s);
}

```

Letters are expected in uppercase.
> 2 votes

# Answer
# 05AB1E, 17 bytes

```
SaJ¹á{R¹þ{«vyay.;

```

Try it online!

---

```
SaJ               # Push 1 if letter 0 else, for all letters in string.
   ¹á{R           # Reverse sort letters from input.
       ¹þ{        # Regular sort digits from input.
          «       # Concatenate those two things.
           v      # For each letter in the sorted string...
            ya    # 0 if digit, 1 if letter.
              y.; # Replace first instance of 0/1 with digit/letter.

```

---

Using the sort-by closure actually was worse: `Σ©Ç®ai0<*}}¹SaJsvyay.;`
> 2 votes

# Answer
## Haskell, 108 bytes

There may be shorter ways, but I just had to try it with the `Lens` library.

```
import Control.Lens
import Data.List
i(!)f=partsOf(traverse.filtered(!'='))%~f.sort
f x=x&i(<)id&i(>)reverse

```

I could define `f` to just be the composition of the two `i` invocations, but I'd still have to apply `x` to it to avoid a type error from the monomorphism restriction. Note that the type of `f` is `Traversable t => t Char -> t Char` so it can be used with `String`s which are lists of `Char`s as well as with arrays of `Char`s.

Here are the test cases:

```
*Main> map f ["5ax36b","321","abc","","2321"]
["3xb56a","123","cba","","1223"]

```
> 2 votes

# Answer
# Python 3, 77 bytes

This answer is based on the comment that says you can use '1', '2', etc if chars and digits are not comparable in the language. 'a' and 1 are not comparable in Python 3.

```
def f(s):x=sorted(s,key=lambda c:ord(c)-95);return[x.pop(-(c>'.'))for c in s]

```
> 2 votes

# Answer
# PHP, 66 bytes:

```
for($a=$argv,sort($a);a&$c=$argv[++$i];)echo$a[$c<A?++$k:--$argc];

```

takes input from command line arguments, prints a string. Run with `-nr` or try it online.

Yields a warning in PHP 7.1; replace `a&` with `""<` to fix.
> 2 votes

# Answer
# APL (Dyalog), 26 bytes

```
a[⍒i][⍋⍋27>i←(⎕a,⌽⍳9)⍳a←⎕]

```

(uses `⎕IO=1`)

Try it online!
> 2 votes

# Answer
# Uiua, 24 bytes

```
⍜▽(⊏⍏.)¬⊃∘⍜▽(⊏⍖.)⊐∵type.

```

Try it!

```
⍜▽(⊏⍏.)¬⊃∘⍜▽(⊏⍖.)⊐∵type.
                       .  # duplicate
                 ⊐∵type   # mask of types (0 for number, 1 for character)
          ⍜▽(⊏⍖.)         # descending sort the characters
        ⊃∘                # keep the mask
       ¬                  # not
⍜▽(⊏⍏.)                   # ascending sort the numbers

```
> 2 votes

# Answer
# K (ngn/k), 26 bytes

```
{x[>i]@<<1>i:x*1 1'`c=@'x}

```

Derived from @ngn's APL solution

Try it online!
> 2 votes

# Answer
# Mathematica, 107 bytes

```
(s=#;s[[p]]=Sort[s[[p=#&@@@s~($=Position)~_String]],#2~Order~#>0&];s[[c]]=Sort@s[[c=#&@@@s~$~_Integer]];s)&

```
> 1 votes

# Answer
# C# (.NET Core), 171 bytes

```
a=>{var b=a.Where(x=>x is int).ToList();b.Sort();int i=0,j=0;return a.Select(x=>b.Contains(x)?b[i++]:a.Except(b).OrderByDescending(y=>y).ToList()[j++]);}

```

Byte count also includes:

```
using System.Linq;

```

Try it online!

Explanation:

```
a =>
{
    var b = a.Where(x => x is int).ToList(); // Filter to only ints and transform to list
    b.Sort();                                // Sort the list
    int i = 0, j = 0;                        // Create index counters
    return a.Select(x =>                     // Replace each input element with
                    b.Contains(x) ?          // If it is in list b:
                    b[i++] :                 // Get the next element from b
                    a.Except(b)              // Otherwise take input and filter out those in b
                     .OrderByDescending(x=>x)// Order them z to a
                     .ToList()[j++]);        // Get the next element

```
> 1 votes

# Answer
# Perl 5, 107 + 1 (-n) = 108 bytes

```
y/][//d;@a=split/, /;@l=sort grep/\D/,@a;@d=sort grep/\d/,@a;@r=map{/\d/?pop@d:shift@l}@a;$"=", ";say"[@r]"

```

Try it online!
> 1 votes

# Answer
# Ruby, 265 bytes

```
x.sort_by(&:to_s).select{|a| a.is_a?(String)}.zip(x.map.with_index {|a, i| a.is_a?(String) ? i : nil}.compact).each{|a,i| x[i] = a}
x.sort_by(&:to_s).select{|a| a.is_a?(Integer)}.zip(x.map.with_index {|a, i| a.is_a?(Integer) ? i : nil}.compact).each{|a,i| x[i] = a}

```

Try it online!

First timer here, My solution is definetly not the best one. But since this is my first answer, I thought in posting just for the fun of it.

Looking foward to see better Ruby answers, to see what is the best approach. I hope I improve in future answers =)

Readable

```
x = ["c", 1, "a", 3, "b", 2]

b = x.map.with_index {|a, i| a.is_a?(Integer) ? i : nil}.compact
s = x.map.with_index {|a, i| a.is_a?(String) ? i : nil}.compact

o = x.sort_by(&:to_s).select{|a| a.is_a?(Integer)}
d = x.sort_by(&:to_s).select{|a| a.is_a?(String)}

d.zip s
d.zip(s).each {|a, i| x[i] = a}

o.zip b
o.zip(b).each {|a, i| x[i] = a }

p x

```
> 1 votes

# Answer
# Python 3, 91 bytes

```
def f(s):x=sorted(s,key=lambda c:(type(c)==str,c));return[x.pop(-(type(c)==str))for c in s]

```
> 1 votes

# Answer
## Clojure, 151 bytes

```
#(map(fn[t c](nth((if(=(type 1)t)vec reverse)(sort((group-by type %)t)))(-(c t)1)))(map type %)(reductions(partial merge-with +)(for[i %]{(type i)1})))

```

Example:

```
(def f #( ... ))
(f [5 \a \x 3 6 \b])
; (3 \x \b 5 6 \a)

```

This calculates the cumulative ~~sum~~ count of integers and characters, and uses it to lookup the correct element from a sorted list of corresponding type's elements.
> 1 votes

# Answer
# Zsh, 43 ~~55~~ ~~70~~ ~~95~~ bytes

```
b=(${(n)@});for i;echo $b[$[#i>64?--k:++j]]

```

Try it online! ~~55bytes~~ ~~70bytes~~ ~~95bytes~~

Create a sorted array `b`, numbers first. Iterate over the arguments. If `i` is a letter (\>ascii #64) then decrement `k` and print `b[k]`, (e.g. `b[-2]` is the 2nd to last value). If `i` is a number, increment `j` and print `b[j]`.

NB: Previously I forgot to **decrease** letters. Fixed now, and saved bytes!
> 1 votes

# Answer
# Go, 290 bytes

```
import."sort"
func f(I[]any){J,K:=StringSlice{},IntSlice{}
var L,M[]int
for i,e:=range I{switch e:=e.(type){case string:J,L=append(J,e),append(L,i)
case int:K,M=append(K,e),append(M,i)}}
Sort(Reverse(J))
Sort(K)
x:=len(L)
for i:=0;i<x+len(M);i++{if i<x{I[L[i]]=J[i]}else{I[M[i-x]]=K[i-x]}}}

```

Attempt This Online!

### Explanation

```
import."sort"                 // boilerplate
func f(I[]any){               // boilerplate
J,K:=StringSlice{},IntSlice{} // J and K store the actual elements
var L,M[]int                  // L and M store their indexes
for i,e:=range I{             // for each element,
switch e:=e.(type){           // switch on their type
case string:J,L=append(J,e),append(L,i) // put strings in J/L
case int:K,M=append(K,e),append(M,i)}}  // put ints in K/M
Sort(Reverse(J))              // sort J reversed (descending)
Sort(K)                       // sort K normally (ascending)
x:=len(L)                     //
for i:=0;i<x+len(M);i++{      // combined loop
if i<x{I[L[i]]=J[i]}          // put the strings back in
else{I[M[i-x]]=K[i-x]}}}      // put the ints back in

```
> 1 votes

# Answer
# Uiua, 21 bytes

```
⍜⊕□⊐∵(⊏⍖⍣¬⟜∘.)⊐∵type.

```

Try it!

Takes an array of boxes, where each box contains either a single number or character.

```
⍜⊕□⊐∵(⊏⍖⍣¬⟜∘.)⊐∵type.
                   ⊐∵type    type of each element; 0 if number, 1 if character
⍜⊕□⊐∵(         )        .   operate on each group...
            ⍣¬⟜∘              for numbers, negate; for characters, identity
         ⊏⍖     .             sort descending by the above

```

A fun 22 bytes:

```
⍥(-∶@0⍜▽(⊏⍖.)⊐∵type.)2
⍥(                      )2    do this twice...
                ⊐∵type        type of each element
       ⍜▽(   )        .      keep characters, operate on it, and put it back
                               to the original array:
            ⊏⍖.                 sort descending
  -∶@0                         replace each element with '0' minus that;
                               this changes characters to numbers and vice versa
                               and reverses the sorting order

```
> 1 votes

# Answer
# 05AB1E, 14 bytes

```
{Ivydićˆë¤ˆ¨]¯

```

Try it online or verify all test cases.

**Explanation:**

```
{         # Sort the (implicit) input-list, which will put all sorted digits at the
          # front, and all sorted letters at the end
 I        # Push the input-list again
  v       # For-each over its items `y`:
   ydi    #  If the current character `y` is a digit:
      ć   #   Extract the head of the sorted-list; pop and push remainder-list and first
          #   item separated to the stack
       ˆ  #   Pop and add this first item to the global array
     ë    #  Else (it's a letter instead):
      ¤   #   Get the last item of the sorted list (without popping the list itself)
       ˆ  #   Pop and add this last item to the global array
        ¨ #   And then remove this last item from the list
  ]       # Close both the if-else statement and loop
   ¯      # And push the global array
          # (after which it is output implicitly as result)

```
> 0 votes

---
Tags: code-golf, array, sorting
---


# Question
Title: 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.

# Answer
# 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

```
> 12 votes

# Answer
# sed, 12

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

```

Try it online!
> 18 votes

# Answer
# 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.)
> 14 votes

# Answer
# 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.
> 10 votes

# Answer
# 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:
> 10 votes

# Answer
# 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.
> 9 votes

# Answer
# , 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.
> 7 votes

# Answer
# 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!.
> 7 votes

# Answer
# Haskell, 24 bytes

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

```

Try it online!
> 7 votes

# Answer
# 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.
> 6 votes

# Answer
# 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*s``3e*`.
> 6 votes

# Answer
# Python 3,  ~~43 41~~  39 bytes

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

```
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, ...`
> 5 votes

# Answer
# 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

```
> 5 votes

# Answer
# Scratch 3.0, 25 blocks/179 bytes

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 on~~line~~ Scratch!
> 5 votes

# Answer
# 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.
> 5 votes

# Answer
# Vyxal, ~~5~~ 3 bytes

```
3•y

```

Try it Online!

```
3•  # Repeat each character three times
  y # Get every other character

```
> 5 votes

# Answer
# 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!
> 4 votes

# Answer
# 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

```
> 4 votes

# Answer
# 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.
> 4 votes

# Answer
# 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!
> 3 votes

# Answer
# 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!
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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!
> 3 votes

# Answer
# 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)

```
> 3 votes

# Answer
# PowerShell, ~~40~~ ~~38~~ 37 bytes

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

```

Try it online!

Takes input `$args`, transforms it `t`oCharArra`y`, 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.*
> 3 votes

# Answer
# Ruby, 25 bytes

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

```

Try it online!
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# Ruby, 25 bytes

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

```

Try it online!

Same byte count as the other answer, different approach.
> 3 votes

# Answer
# 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)
> 3 votes

# Answer
# Pip, 11 bytes

```
B X_%2+1MEa

```

Try it online!

-2 from Dlosc.
> 3 votes

# Answer
# C (gcc), <sup>~~66~~ \\$\cdots\\$ ~~59~~</sup> 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!
> 2 votes

# Answer
# Hexagony, ~~13~~ 12 bytes

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

```

Try it online!

### Expanded

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

```

Uses the very naive read-print, read-print twice approach.
> 2 votes

# Answer
# Red, 51 bytes

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

```

Try it online!
> 2 votes

# Answer
## `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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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.
> 2 votes

# Answer
# Raku, 14 bytes

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

```

Try it online!

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

# Answer
# 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!
> 2 votes

# Answer
# PHP, 37 bytes

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

```

Try it online!
> 2 votes

# Answer
# 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
                           # Jump to function 2 if it equals variable 1
            1o             # Otherwise, output it once
              1r3x1v2e     # Read another byte of input
                           # Jump to function 2 if it equals variable 1
                      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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# JavaScript (V8), ~~76~~ ~~68~~ ~~56~~ ~~48~~ 44 bytes

Thanks to Malivil for 12 bytes !

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

```

Try it online!
> 2 votes

# Answer
# brainfuck, 18 bytes

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

```

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

Try it online!
> 2 votes

# Answer
# Perl 5 `-p`, 13 bytes

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

```

Try it online!
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# PowerShell, 26 bytes

```
$args-replace'.(.)','$0$1'

```

Try it online!
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# 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

```
> 2 votes

# Answer
# .+?, 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)
> 2 votes

# Answer
# GNU AWK, 36 bytes

```
BEGIN{RS=".|";ORS=e}$0=NR%2?RT:RT RT

```

```
BEGIN{RS=".|";ORS=e}  This reads one character at a time,
                      which can be retrieved by the RT variable.

$0=NR%2?RT:RT RT      If NR=1 (mod 2), i.e., True, assigns "RT" to the output.
                      Otherwise, assigns "RT RT", which is RT concatenated to itself.
                      This conditional simply doubles the even occurrences.

```

Try it online!
> 2 votes

# Answer
# Pip, 10 bytes

```
WV(UWa!*h)

```

Try it online!

### Explanation

I love it when I can abuse built-in numbers for some other purpose.

```
WV(UWa!*h)
     a      First command-line argument
   UW       Unweave into a list of two strings, each containing every other character
        h   100
      !*    Logically negate each digit
  (      )  Index into the list using each of those values
WV          Weave the resulting list of three strings back together

```

For instance, if the input is `abcde`:

```
   UWa      ["ace"; "bd"]
      !*h   [0; 1; 1]
  (      )  ["ace"; "bd"; "bd"]
WV          "abbcdde"

```
> 2 votes

# Answer
## , 13 bytes

```
¤+ōČōōČ

```

## Explanation

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

```
> 1 votes

# Answer
# Funky, 34 bytes

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

```

A pretty simple solution to the problem.

Try it online!
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# APL+WIN, 13 bytes

Prompts for string:

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

```

Try it online! Courtesy of Dyalog Classic.
> 1 votes

# Answer
## Unix TMG, 59 bytes

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

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# PowerShell, 88 bytes

```
$c={param($i)$c=0;$o;$i.toCharArray()|%{if($c%2-eq1){$o+="$_$_"}else{$o+="$_"}$c++;};$o}

```

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!
> 1 votes

# Answer
# C (gcc), 59 bytes

```
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!
> 1 votes

# Answer
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!
> 1 votes

# Answer
# 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.

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# 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!
> 1 votes

# Answer
# Pyth, 9 8 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!
> 1 votes

# Answer
# Chevron \- 96 bytes

(link goes to interpreter)

```
>^__>^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

```
> 1 votes

# Answer
# T-SQL, 88 bytes

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

```

**Try it online**
> 1 votes

# Answer
# Retina, 9 bytes

```
.(.)
$0$1

```

Port of *@DigitalTrauma*'s sed's answer, so make sure to upvote him as well!

Try it online.

**Explanation:**

```
.(.)  # MATCH:
.(.)  #  Every pair of characters,
      #  where the second character is saved in capture group 1

$0$1  # And replace it with:
$0    #  The entire match, so both characters
  $1  #  Followed by the character from capture group 1

```
> 1 votes

# Answer
# Java 8, 30 bytes

```
s->s.replaceAll(".(.)","$0$1")

```

Same approach as my Retina answer, which was a port of *@DigitalTrauma*'s sed's answer.

Try it online.
> 1 votes

# Answer
# Clojure, 91 bytes

```
(defn d[s](apply str(map #(str(first %)(second %)(second %))(partition-all 2 2(into[]s)))))

```

Ungolfed version:

```
(defn dup-alternate-chars[s]
  (apply str (map #(str (first %) (second %) (second %)) (partition-all 2 2 (into [] s)))))

```

Test harness:

```
(println (d "abcde"))

```

which prints "abbcdde".

Try it online!
> 1 votes

# Answer
# APL (dzaima/APL), ~~10~~ 9 bytes

-1 thanks to Bubbler

Anonymous tacit prefix function. Requires 0-based indexing (`⎕IO←0`)

```
⊢⌿⍨1 2⍴⍨≢

```

Try it online!

the length

`2⍴⍨` use that to cyclically **r**eshape `[1,2]`

`⊢⌿⍨` use that to replicate the letters
> 1 votes

# Answer
# Rabbit~, 13

```
_[.0:.>:.:.>]

```

Explanation:

```
_ - Move to input
 [.0 - start loop with input 0, and loop until you hit 0
    :. - print
      > - move along input
       :.:. - print twice
           > - move along input
            ] - end loop if we have reached past input

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 30 bytes

```
StringReplace[a_~~b_:>a<>b<>b]

```

Try it online!

For every non-overlapping pair of characters, appends the second character.

`""<>MapAt[#<>#&,#,;;;;2]&` doesn't work on an empty input.
> 1 votes

# Answer
# Ly, 17 bytes

```
irs[l!s[p:o0]po]>

```

Try it online!

This is pretty much a direct translation of the description of the challenge. It reads in the all the input, then loops over the list printing each character once or twice.

```
ir                - read input as codepoints onto the stack, reverse the stack
  s               - save a codepoint to the backup cell, just has to be non-zero
   [           ]  - loop while the stack isn't empty
    l!s           - load the backup cell, flip 1/0, save it back
       [   0]p    - if/then, true for even numbered chars
        p         - pop (delete) the if/then test boolean
         :o       - duplicate top of stack and print as char
              o   - print the top of stack as a char
                > - switch stacks to avoid auto-printing

```
> 1 votes

# Answer
# TI-Basic, 39 bytes

```
For(I,2,1.5length(Ans),3
sub(Ans,1,I)+sub(Ans,I,1-I+length(Ans
End

```

Same as this answer except for the first line. Input is taken in `Ans`. Output is stored in `Ans`.
> 1 votes

# Answer
# APL (Dyalog Unicode), 11 chars

```
⊢(/⍨)1 2⍴⍨⍴

```

```
           ⍴   monadic: shape of the right argument (number of elements)

      1 2⍴⍨    repeat numbers 1 and 2 as many times as the right argument

⊢              the right argument

 (/⍨)          replicate each element of the left argument as many times as
               specified by the corresponding elements of the right argument

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `t`, 3 bytes

```
3Ḅz

```

Attempt This Online!

Port of emanresu A's Vyxal answer.

### Thunno 2 `J`, 5 bytes

```
dŻɗ⁺×

```

Attempt This Online!

#### Explanation

```
3Ḅz  # Implicit input                      ->  "abcde"
3Ḅ   # Repeat each character three times   ->  "aaabbbcccdddeee"
  z  # Uninterleave into two parts         ->  ["aabccdee","abbcdde"]
     # Implicit output of last item        ->  "abbcdde"

```

```
dŻɗ⁺×  # Implicit input                    ->  "abcde"
d      # Cast to list of characters        ->  ["a","b","c","d","e"]
 Ż     # Push the length range             ->  ["a","b","c","d","e"]  [0,1,2,3,4]
  ɗ    # Pop and push each item mod two    ->  ["a","b","c","d","e"]  [0,1,0,1,0]
   ⁺   # Increment each value in the list  ->  ["a","b","c","d","e"]  [1,2,1,2,1]
    ×  # Multiply the two lists together   ->  ["a","bb","c","dd","e"]
       # Implicit output of joined list    ->  "abbcdde"

```
> 1 votes

# Answer
# Arturo, 26 bytes

```
$=>[replace&{/.(.)}"$0$1"]

```

And non-regex:

# Arturo, 41 bytes

```
$=>[i:0loop&=>[&if=1i%2[++<=]prints'i+1]]

```

Try it!
> 1 votes

# Answer
# Grass, 47 bytes

```
wWWWWWwWWWWWWwwWWWWwwWWWWWwwWWWWWWwWWWWWWwwwwww

```

Try it online!

Exits with an error after printing out the string.

Ungolfed version:

```
w             (Function takes one argument)
WWWWWw        (Take one character from stdin)
WWWWWWww      (Take another character from stdin)
WWWWww        (Print first character, or error if no characters left)
WWWWWww       (Print second character, or error if no characters left)
WWWWWWw       (Print second character again)
WWWWWWwwwwww  (Call this function again)

```
> 1 votes

# Answer
# Factor \+ `sequences.repeating`, 19 bytes

```
[ 3 repeat <odds> ]

```

Attempt This Online!

Repeat each character three times and take every other character starting with the second one. Port of emanresu A's Vyxal answer.
> 0 votes

# Answer
# Python, 62 bytes

```
lambda s:''.join(c if i%2==0 else 2*c for i,c in enumerate(s))

```

Try it online!
> 0 votes

# Answer
# Fig, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
n2@h

```

Try it online!

```
n2@h
n @  # For every
 2   # Second character
   h # Double

```
> 0 votes

# Answer
# Zsh, 32 bytes

```
for a b (`fold -1`)printf $a$b$b

```

Try it online!
> 0 votes

# Answer
# Uiua, 8 bytes

```
▽+1◿2⇡⧻.

```

Try it!

```
▽+1◿2⇡⧻.
       .  # duplicate
      ⧻   # length
     ⇡    # range
   ◿2     # modulo two
 +1       # increment
▽         # keep

```
> 0 votes

---
Tags: code-golf, string
---