title: Swap every two elements in a list

text:
# Question
Title: Swap every two elements in a list
## Challenge

Let's have a list `L` of `n` elements. The task is to swap every two elements in this list.

## Constrains

* the list `L` has at least two elements
* size of the list `L` is a multiple of two (i.e. number of elements is even)

### Example

* input: `[1,2,3,4,5,6]`
* output: `[2,1,4,3,6,5]`
* input: `[0,1,0,1]`
* output: `[1,0,1,0]`

## Rules

# Answer
# \>\<\>, ~~4~~ 3 bytes

```
i#o

```

Try it online!

Lol, \>\<\> ~~ties with~~ beats Jelly & 05AB1E. Terminates with an error.

-1 thanks to @Manny Queen.

# How does it work?

```
     The instruction pointer (IP) is currently moving right
i    Take input as a character
 #   Reflect - The IP starts moving left
i    Take input again
  o  Output that
 #   Reflect - The IP starts moving right again
  o  Output the first input we took - the inputs are now swapped

And now, we're moving left and back at the start again on i + moving right.
This loops forever (i.e. until erroring when we're out of input)
because there is no halt instruction (;)
This is essentially executing "iioo" in an infinite loop.

```
> 21 votes

# Answer
# Vyxal `r`, 2 bytes

```
yY

```

Try it Online!

Explanation:

```
y  # Uninterleave
 Y # Interleave

```
> 13 votes

# Answer
# Python 3, 34 bytes

```
f=lambda l:l and l[1::-1]+f(l[2:])

```

Try it online!

When `l` is empty (which makes it falsy), return it directly. Otherwise, reverse the first two elements and make a recursive call for the rest.
> 12 votes

# Answer
# convey, 7 bytes

I knew I should have implemented SpaceChem's flipflop operator, then this would be 5 bytes. :-)

*-6 byte by @Manny Queen*

```
}?{
}~1

```

Try it online!

`{` puts the input list on the conveyor, `}` prints the result. On the `?` the elements try to go down if they can. On the `~` they will wait for `1` tick before going to the output, thus starting with the first item, every second element is delayed for two ticks.

### 13 bytes

```
},<
{@^
0"
1^

```

Try it online!

The lower loop `0"\1^` copies `0 1 0 1 …` into choose `@`. The input is thus split into two paths. The right one takes a little bit longer, so the other number can overtake it before joining `,` again.
> 12 votes

# Answer
# Haskell, 22 bytes

```
f(a:b:c)=b:a:f c
f x=x

```

Try it online!
> 12 votes

# Answer
# brainfuck, 9 bytes

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

```

Try it online!
> 11 votes

# Answer
# Rust v1.37.0, ~~59~~ ~~55~~ 47 bytes

```
|a:&[_]|(0..).zip(a).map(|i|a[i.0^1]).collect()

```

Try it online!

*-2 bytes thanks to ZippyMagician*
*-2 bytes thanks to alephalpha*
*-8 bytes thanks to `(0..).zip(a)`*

Rust is not a golfy language...
Port of the C# and JS answers
v1.37.0 is the version available on TIO

# Rust stable, 54 bytes

```
|a:&[_]|a.chunks(2).flat_map(|a|[a[1],a[0]]).collect()

```

Try it online!

Thanks to ZippyMagician for this *slightly* golfier answer on the latest version of Rust.
> 10 votes

# Answer
# Python 2, 30 bytes

```
def f(a,b,*m):print b,a,;f(*m)

```

Try it online!

The function `f` takes input splatted like `f(1,2,3,4,5,6)`, and prints the output space-separated, terminating with error.

---

**34 bytes**

```
lambda l:map(l.pop,len(l)/2*[1,0])

```

Try it online!

This works by alternating popping the elements at index `1` and index `0`.
> 9 votes

# Answer
# Wolfram Language (Mathematica), 22 bytes

```
0<##<1||#2&&#&&#0@##3&

```

Try it online!

Input `[L...]`, and returns in an `And`. Works on integer inputs.

---

### Wolfram Language (Mathematica), 24 bytes

```
{}=={##}||#2&&#&&#0@##3&

```

Try it online!

Input `[L...]`, and returns in an `And`. Works on non-boolean inputs.

### Wolfram Language (Mathematica), 26 bytes

```
#2~##&~#&@@@#~Partition~2&

```

Try it online!

Input `[L]`, and returns a list. Works.
> 7 votes

# Answer
# JavaScript (ES6), 23 bytes

```
x=>x.map((_,i)=>x[i^1])

```

The `[i^1]` is thanks to m90 in TNB

Try it online!
> 6 votes

# Answer
# Python 3, 36 bytes

```
lambda a:sum(zip(a[1::2],a[::2]),())

```

Try it online!
> 5 votes

# Answer
# Python 3 \+ numpy, 31 bytes

```
lambda m:m[~-(m==m).cumsum()^1]

```

Try it online!

Expects a numpy array. Most of the code is about avoiding referencing numpy directly, so we can avoid the explicit import. It then calculates the indices directly by xoring a counter with 1.
> 5 votes

# Answer
# Ly, 7 bytes

```
ir[foo]

```

Try it online!

Pretty straightforward, but might be worth posting since it's almost pronounceable. :)

```
ir       -- read input codepoints into the stack, reverse the order
  [   ]  -- while the stack isn't empty
   foo   -- flip the top two entries and print as characters

```

# Cubix, 14 bytes

```
..@.i?i.o;o;.^

```

Try it online!

This is the first time I've tried to use Cubix, so I wouldn't be suprised if it's possible to do this with less code. It's a hard language to explain, since it's a 2D language where the code is wrapped around a cube. So the directions the instruction pointer take a hard to show in a description. I'll include a link to the online interpreter since it has a debug mode when you can see the way the code iterates through the cells.

But I'll try to explain it too...

```
..@.i?i.o;o;.^ - code before it's wrapped on the cube...
    i          - (1) starts here, input a codepoint
     ?         - branch if top of stack, <0 "left", >0 "right"
  @            - "left" (true on EOF), halt program
             ^ - "right", set IP direction to "up"
     ?         - same branch, but coming from another direction
      i        - "right", input another codepoint
        o;     - output top of stack as char, pop it off stack
          o;   - repeat... code wraps back to (1)

```

The `.` characters are no-ops and are needed to place the other characters in the right position so they will wrap into place on the cube.

Here's a link to the online interpreter http://ethproductions.github.io/cubix/?code=Li5ALmk/aS5vO287Ll4=&input=MTIzNDU2Nzg=&speed=20
> 5 votes

# Answer
# C (clang), ~~53~~ \\$\cdots\\$ ~~43~~ 42 bytes

```
f(*l,n){*l^=l[1]^(l[1]=*l);n&&f(l+2,n-2);}

```

Try it online!

Inputs a pointer in an `int` array and the array's length (since pointers in C carry no length info).
Swaps every two elements in place.
> 4 votes

# Answer
# Python 3.8 (pre-release), 35 bytes

```
def f(m):*m[1:],_,m[::2]=*m,m[1::2]

```

Try it online!

In-place. Essentially a golfed version of `m[1::2],m[::2]=m[::2],m[1::2]`
> 4 votes

# Answer
# , 29 bytes

```
function(l)l[seq(!l)+2*1:0-1]

```

Try it online!
> 4 votes

# Answer
# Desmos, ~~39~~ 38 bytes

```
l=[1...L.length]
f(L)=L[l-1+2mod(l,2)]

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 4 votes

# Answer
# Ruby, 26 bytes

```
->l{r=-1;l.map{l[1^r+=1]}}

```

Try it online!
> 4 votes

# Answer
# , 9 bytes

```
[:,_2|.\]

```

Try it online!
> 4 votes

# Answer
# T-SQL, 32 bytes

Input is a table variable

```
SELECT a FROM @ ORDER BY b+b%2*2

```

**Try it online**
> 4 votes

# Answer
# , 22 bytes

```
3.72082072152152072094

```

Try it online!

Readable + explanation:

```
3. 720 820 721 521 520 720 9 4
^^------------------------------ mandatory prefix
   ^^^-------------------------- initial input in cell 20
       ^^^-----------------^---- loop while cell 20 is nonzero
           ^^^------------------ input to cell 21
               ^^^-------------- output cell 21
                   ^^^---------- output cell 20
                       ^^^------ input to cell 20
                           ^---- end loop
                             ^-- exit

```

Corresponding Quartic program:

```
decl a, b
input a
loop a
  input b
  print b
  print a
  input a
end

```
> 4 votes

# Answer
# AWK, 43 41 bytes

```
{for(;++n<NF;n++)$n+=$(n+1)-($(n+1)=$n)}1

```

*Thanks for Dominic van Essen for 2 less bytes!*

Try it online!

```
{
for(;++n<NF;n++)        Starts a loop though the numbers.
                        n has to start as 1, because $0 is the whole line.
$n+=$(n+1)-($(n+1)=$n)  Swap the numbers two by two.
                        Readable: a += b - (b = a)
}
1                       Prints the line.

```
> 4 votes

# Answer
# CLC-INTERCAL, ~~95~~ 67 bytes.

Why does CLC-INTERCAL 1.-94.-2 lack `!1~.1'`? I could have golfed off one byte.

```
DOCOMEFROM#9(1)DOWRITEIN.1+.2DDOCOMEFROM'.1~.1'~#1(9)DOREADOUT.2+.1

```

Copy and paste to try it online!

## Usage

* Each item of list must be in `ONE` to `SIX FIVE FIVE THREE FIVE` (inclusive); `ZERO` for end of list.
    + Given from STDIN, delimited with a LF.
* Outputs to STDOUT, as roman number.

## Try these inputs

```
ONE
TWO
ONE
TWO
ZERO

```

```
ONE
TWO
THREE
FOUR
FIVE
SIX
ZERO

```
> 4 votes

# Answer
# BQN, ~~10~~ 9 bytesSBCS

-1 byte thanks to Razetime!

```
⥊·⌽˘∘‿2⊸⥊

```

Run online!

`∘‿2⥊` Reshape the input into a matrix with 2 columns and and the necessary number of rows.
`⌽˘` Reverse horizontally (Swap the 2 columns).
Flatten into a vector.

An alternative using the *Under* operator at 10 bytes:

```
⌽˘⌾(∘‿2⊸⥊)

```

Try it online!
> 4 votes

# Answer
# Jelly, 4 bytes

```
s2UF

```

Try It Online!

```
s2    Slices of length 2
  U   Reverse each
   F  Flatten

```
> 3 votes

# Answer
# Perl 5 -p, 21 bytes

```
s/(\S+) (\S+)/$2 $1/g

```

Try it online!
> 3 votes

# Answer
# Add++, 57 bytes

```
a:?
b:0
n:0
m:3
`b
Ea,Ib=n,,b:1,,x:i,+1,Ib=m,,b:0,,Oi,,Ox

```

Try it online!

Input is the first argument.
> 3 votes

# Answer
# Raku, ~~19~~ 17 bytes

~~\*.flatmap:{$^b,$^a}~~

```
*[^* »+»<1 -1>]

```

Try it online!

* `*[...]` is an anonymous function that slices into the list given as the sole argument using the bracketed expression, which is another anonymous function.
* `^* »+» <1 -1>` takes the numbers from 0 up to one less than the argument, and produces a new list by alternatively adding 1 and -1. Those reordered indices are used to slice into the original input array.
> 3 votes

# Answer
# APL+WIN, 17 bytes

Prompts for vector

```
,⌽((.5×⍴r),2)⍴r←⎕

```

Try it online! Thanks to Dyalog Classic
> 3 votes

# Answer
# C# (.NET Core) with `Linq`, ~~32~~ 26 bytes

```
a=>a.Select((n,i)=>a[i^1])

```

Try it online!

*-8 bytes thanks to m90's witchcraft*

# C# (.NET Core), 73 bytes

```
a=>{for(int i=0,d=0;i<a.Length;i++){d=a[i];a[i]=a[++i];a[i]=d;}return a;}

```

Try it online!
> 3 votes

# Answer
# Zsh, 18 bytes

```
for a b;<<<$b<<<$a
```

Attempt This Online!
> 3 votes

# Answer
# Factor \+ `sequences.merged`, ~~34~~ 29 bytes

```
[ 2 group unzip swap 2merge ]

```

Try it online!

## Explanation

```
        ! { 1 2 3 4 5 6 }
2 group ! { { 1 2 } { 3 4 } { 5 6 } }
unzip   ! { 1 3 5 } { 2 4 6 }
swap    ! { 2 4 6 } { 1 3 5 }
2merge  ! { 2 1 4 3 6 5 }

```
> 3 votes

# Answer
# Rockstar, 98 bytes

```
Listen to B
cut B with ","
I is 0
while I is less than B
shout B at I+1
shout B at I
Build I up up

```

Try it online!
(Must manually copy-paste code)

Takes input as comma-separated string of numbers eg:

```
1,2,3,4,5,6

```

Outputs as newline-separated string of numbers eg:

```
2
1
4
3
6
5

```

Rockstar has no modulo, and no bitwise operators, so porting the other solutions is out of the question.

### Explanation

```
Listen to B             ; Read input to B
cut B with ","          ; Split B on ","
I is 0                  ; Set I to 0
while I is less than B  ; While I < B.length
                        ; (Rockstar Arrays automatically coerce to length when used as a scalar)
shout B at I+1          ; Print B[I+1] with trailing newline
shout B at I            ; Print B[I] with trailing newline
Build I up up           ; Increment I twice (each 'up' increments)

```
> 3 votes

# Answer
# Japt, 4 bytes

```
ò mé

```

Try it

```
ò      - chunks of 2
  mé   - rotate each

```
> 3 votes

# Answer
# Red, 37 bytes

```
func[a][foreach[b c]a[print[c lf b]]]

```

Try it online!

## Alternative

Much longer but more fun approach using `parse`:

# Red, 59 bytes

```
func[a][parse a[collect[any[b: skip keep skip keep(b/1)]]]]

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 4 bytes

```
2ôí˜

```

Try it online or verify all test cases.

**4 bytes alternatives:**

```
ιRø˜

```

Try it online or verify all test cases.

```
2ô€`

```

Try it online or verify all test cases.

**Explanation:**

```
2ô   # Split the (implicit) input-list into parts of size 2
     #  i.e. [1,2,3,4,5,6] → [[1,2],[3,4],[5,6]]
  í  # Reverse each pair
     #  → [[2,1],[4,3],[6,5]]
   ˜ # Flatten the list of pairs
     #  → [2,1,4,3,6,5]
     # (after which this list is output implicitly as result)

ι    # Uninterleave the (implicit) input-list, using 2 as implicit second argument
     #  i.e. [1,2,3,4,5,6] → [[1,3,5],[2,4,6]]
 R   # Reverse it
     #  → [[2,4,6],[1,3,5]]
  ø  # Zip/transpose, swapping rows/columns
     #  → [[2,1],[4,3],[6,5]]
   ˜ # Flatten the list of pairs
     #  → [2,1,4,3,6,5]
     # (after which this list is output implicitly as result)

2ô   # Split the (implicit) input-list into parts of size 2
     #  i.e. [1,2,3,4,5,6] → [[1,2],[3,4],[5,6]]
  €  # Map over each pair:
   ` #  Pop and push the pair to the stack
     # (€` is usually used to flatten a multi-level list one level down. One side-effect
     # is that the items are dumped in reversed order, which is what we want in this
     # case)
     #  → [2,1,4,3,6,5]
     # (after which this list is output implicitly as result)

```
> 3 votes

# Answer
# Pure Bash, 32 + 1 = 33 bytes

One additional byte for filename specification: `x`.

```
echo "$2
$1"
shift 2
(($#))&&. x

```

Try it online!

## Usage

* Input from program arguments.
* Outputs to stdout.

---

# Pure Bash, 34 + 1 = 35 bytes

One additional byte for filename specification: `x`.

```
read x
read y||>x
echo "$y
$x"
. x

```

Try it online!

## Usage

* Each item is given from STDIN.
* Outputs to STDOUT.
* Items are separated by a LF.
> 3 votes

# Answer
# Whitespace, 65 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input1][S N
S _Duplicate_input1][S N
S _Duplicate_input1][T  N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input2][T N
S T _Print_input2_as_integer][S S S T   S T S N
_Push_10][S N
S _Duplicate_10][T  N
S S _Print_10_as_character][S N
T   _Swap_top_two][T    N
S T _Print_input1_as_integer][T N
S S _Print_10_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.

Whitespace doesn't have lists, so I/O are newline delimited (strictly non-negative) integers.

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

**Explanation in pseudo-code:**

```
LOOP:
  Integer a = STDIN as integer
  Integer b = STDIN as integer
  Print b as integer to STDOUT
  Print '\n' as character to STDOUT
  Print a as integer to STDOUT
  Print '\n' as character to STDOUT
  Go to next iteration of LOOP

```

This will stop with an error automatically when there are no more inputs.

: For every second input it will use the input before it as heap-address (`[SNS_Duplicate_input1][SNS_Duplicate_input1][TNTT_Read_STDIN_as_integer]`), so the inputs should be strictly non-negative, since negative heap addresses aren't allowed in Whitespace.
> 3 votes

# Answer
# Python 2, ~~49~~ 39 bytes

```
lambda l:[l[c^1]for c in range(len(l))]

```

Try it online!

-10 with thanks to @MannyQueen for an awesome tip.

Simply because no-one has submitted a Python 2 answer yet.
> 3 votes

# Answer
# Vim, 11 bytes

```
qqddpj@qq@q

```

Try it online!

Explanation:

```
qq    @qq@q # Loop:
  dd        #  Delete the line
    p       #  Paste it below the next line
     j      #  Move down a line

```
> 3 votes

# Answer
# APL, 15 bytes

```
{,⌽⍵⍴⍨(2÷⍨≢⍵)2}

```

The same idea as in the existing solution, but implemented as a separate function and two bytes less.
> 3 votes

# Answer
# Nibbles, ~~3.5~~ 3 bytes (6 nibbles)

```
\+\`/~

```

```
   `/      # chunks of input
     ~     # (using default size = 2),
  \        # reverse,
 +         # concatenate,
\          # and reverse again.

```
> 3 votes

# Answer
# Desmos, ~~42~~ 38 bytes

-4 bytes thanks to @aiden's suggestion and wackscope variables

```
l=[1...L.length]
f(L)=L[l-1+2mod(l,2)]

```

Try It On Desmos!
> 3 votes

# Answer
# sed `-n`, 10 bytes

```
2~2{G;p};h

```

Try it online!

* `2~2{G;p}` For even numbered lines, append hold space into pattern space and print
* `h` For all lines, replace hold space with pattern space. This means that the hold space will always contain the previous, odd-numbered line when we are on an even-numbered line.
> 3 votes

# Answer
# Pip `-xp`, ~~5~~ ~~8~~ 7 bytes

```
R_MF<>a

```

Try It Online!
> 3 votes

# Answer
# Rockstar, 63 bytes

Takes input as a space separated string, outputs each element on its own line. 9 bytes could be saved if we were guaranteed every element of the array was a single digit by taking input with no delimiting spaces.

```
listen to S
cut S with " "
while S
roll S in N
say roll S
say N

```

Try it (Code will need to be pasted in)

```
listen to S        :Read the input string into variable S
cut S with " "     :Split S to an array on spaces
while S            :While S is not empty
roll S in N        :  Pop the first element from S into variable N
say roll S         :  Pop the first element from S and output it
say N              :  Output N

```
> 3 votes

# Answer
# Vyxal, 4 bytes

```
2ẇRf

```

Try it Online!

Explanation:

```
2ẇ   # Split list into groups of two
  R  # Reverse each group
   f # Flatten

```
> 2 votes

# Answer
# Grok, 11 bytes

```
:Y}:zpz
  q

```

Try it Online!

Explanation:

```
:Y      # Get input and copy it to the register
  }     # Quit if no more input
  q
   :z   # Print next input
     pz # Print value in the register

```
> 2 votes

# Answer
# ayr, 6 bytes

```
,_2,`/

```

# Explained

```
 _2 … /    pairwise reduce
    ,`     By reverse concatenation
,         Ravel

```
> 2 votes

# Answer
# PowerShell, 31 bytes

```
%{If(++$i%2){$j=$_}Else{$_,$j}}

```

Input comes from the pipeline.

Try it online!

Try it in a PS console:

```
$array = 1,2,3,4,5,6
$result = $array |
%{If(++$i%2){$j=$_}Else{$_,$j}}
"$($array -join ',') --> $($result -join ',')"

```

## Explanation

**%** is an Alias for the Cmdlet "ForEach-Object", which accepts input from the pipeline and processes each incoming object inside the ScriptBlock {...}
**If(++$i%2)** first increments $i (which starts at 0) in each loop and takes it modulo 2
If the result is 1:
**{$j=$\_}** the current element will be saved in in $j
Otherwise (0):
**{$\_,$j}** first puts the current element, then the element from the last loop iteration into the pipeline/stdout.
> 2 votes

# Answer
# Add++, 10 bytes

```
L,2$T€bRbF

```

Try it online!

Uses Add++'s much more powerful functional mode, rather than it's vanilla mode. However, definitely check out the other Add++ answer, as it doesn't use any form of indexing, just looping!

## How it works

```
L,2$T€bRbF - Unnamed lambda function. Takes 1 argument, L
L,         - Define the lambda:
  2$T      - Split into runs of length 2
     €     - Over each:
      bR   -   Reverse it
        bF - Flatten and return

```
> 2 votes

# Answer
# TI-Basic, ~~19~~ 17 bytes

```
seq(Ans(I-i²^I),I,1,dim(Ans

```

`i` represents the imaginary number.

Takes input in `Ans`. Output is stored in `Ans` and is displayed.

-2 bytes thanks to MarcMush.
> 2 votes

# Answer
# CJam, 10 bytes

```
N{riripp}h

```

Try it online!

### Explanation

```
N           e# Push newline (this is truthy)
 {      }h  e# Do while without popping the condition: infinite loop
  r         e# Read line and push string to the stack
   i        e# Interpret as integer
    r       e# Read line and push string to the stack
     i      e# Interpret as integer
      p     e# Pop and print with a newline
       p    e# Pop and print with a newline
            e# Implicitly print stack: newline

```
> 2 votes

# Answer
# Pari/GP, 27 bytes

```
l->[l[i-(-1)^i]|i<-[1..#l]]

```

Try it online!
> 2 votes

# Answer
# x86-16 machine code, ~~8~~ 7 bytes

```
00000000: aca4 aa49 e2fa c3                        ...I...

```

Listing:

```
    TWO_LOOP:
AC      LODSB               ; load first byte (into AL)
A4      MOVSB               ; move second byte into first byte
AA      STOSB               ; store first byte (from AL) into second byte
49      DEC  CX             ; only loop half as many times as length
E2 F9   LOOP TWO_LOOP
C3      RET

```

Callable function: input list at `[SI]`, output to `[DI]` length in `CX`.

-1 bytes thx to @m90!
> 2 votes

# Answer
# Pxem, 18 + 0 = 18 bytes.

The configure is:

* No breaking loop when insufficient items.
* Abort to illegal integer input.

Filename:

```
.w._._.n .o.n .o.a

```

Content is empty.

Try it online!

## Usage

* With STDIN and STDOUT.
* Each integer shall be given, separated by one or more space characters.
* Outputted separated with a space.
> 2 votes

# Answer
# Coconut, 48 bytes

```
l->(l[1::2],l[:-1:2])|*>zip|>reduce$(+)

```

Try it online!

Python equivalent:

```
from functools import reduce
from operator import add
f = lambda l: reduce(add, zip(l[1::2], l[:-1:2]))

```
> 2 votes

# Answer
# C++ (gcc), 50 bytes

```
[](auto&v){for(int&i:v)swap(i,(&i)[int(&i)%8<1]);}

```

-5 bytes thanks to ceilingcat!

Try it online!
> 2 votes

# Answer
# Burlesque, 6 bytes

```
2co)^p

```

Try it online!

Improved: Remembered map shorthand

```
2co   # Chunks of 2
)^p   # Push in reverse for each block

```

# Burlesque, 7 bytes

```
2co{}^m

```

Try it online!

```
2co   # Chunks of 2
{}^m  # Push in reverse for each block (strictly push-map with a nop)

```
> 2 votes

# Answer
# Husk, 4 bytes

```
ṁ↔C2

```

Try it online!

### Explanation

```
ṁ↔C2
  C2  slices of length 2
ṁ↔    flatmap reverse

```
> 2 votes

# Answer
# Brachylog, 5 bytes

```
ġ₂↔ᵐc

```

Try it online!

### Explanation

```
ġ₂         Split the list in groups of 2 consecutive elements
  ↔ᵐ       Map reverse
    c      Concatenate

```
> 2 votes

# Answer
# Knight, 35 bytes

```
;=aP;=bP WaIb;Ob;Oa;=bN=aP Ia=bP=aP

```

Try it online!
> 2 votes

# Answer
# rSNBATWPL, 37 bytes

```
a~(a cond (a{1},0 a)+{a sfro 2}){+for

```

This is very golfed. It is "bad rSNBATWPL" in that it abuses the syntax very heavily. The ungolfed version of this is:

```
f = a ~ cond{a} {
    (a{1}, a{0}) conc f{a sfro 2}
} { cast.array{""} }

```

This is a simple recursive lambda function, which iterates pair-by-pair. Some golfs I made to this were:

* Removing whitespace and the unnecessary trailing `}`, of course
* Substituting `cast.array{""}` for `+for`, a very strange way of generating an empty array (works by iterating with a function, `+` in this case, over an empty array generated when `for` casts its right input, which is `Null`, to an array)
* Replacing `conc`, the concat function, with `+`
* Replacing `a{0}` with `0 a`, which calls `a` as a curried binary function. Its second argument is `Null`, and since calling any primitive value as a function with `Null` as its input returns it unchanged, this saves a byte for little cost
* Running `cond` as a binary function. Since rSNBATWPL functions/built-ins are curried, this saves a byte over applying the function three times (which is the traditional way of providing three arguments)
* Replacing `f=` and `f{...}` with an implicit recursive call. `.` is a variable which always refers to the current function, so `f{...}` can be replaced with `.{...}` to remove the `f=`, and any time there's a `{...}` without a function name, an implicit `.` is added, allowing me to save another byte by putting it after the `+`
> 2 votes

# Answer
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
ZlrzZS

```

Attempt This Online!

#### Explanation

```
ZlrzZS  # Implicit input     [1, 2, 3, 4, 5, 6]
Zl      # Uninterleave       [[1, 3, 5], [2, 4, 6]]
  r     # Reverse            [[2, 4, 6], [1, 3, 5]]
   zZ   # Zip                [[2, 1], [4, 3], [6, 5]]
     S  # Sum (Flatten)      [2, 1, 4, 3, 6, 5]

```
> 2 votes

# Answer
# Uiua SBCS, 7 bytes

```
♭≡⇌↯∞_2

```

Try it!

-1 thanks to Bubbler

```
♭≡⇌↯∞_2
   ↯∞_2  # reshape into matrix with two columns
 ≡⇌      # reverse columns
♭        # deshape

```
> 2 votes

# Answer
# Labyrinth, 13 bytes

```
??!
; \
,\!
@

```

Try it online!

Takes a list of integers separated by any non-numeric non-null single byte, and prints newline-separated integers. It is important that the input does NOT have a trailing separator, since it is used to detect the end of input.

```
Loop: ??!\!\,;
??    Take two integers A and B [A B]
!\!\  Print B, newline, A, newline
,     Take the next separator, -1 on EOF
;     Continue loop if not EOF; discard the separator

End: @ (Halt)

```
> 2 votes

# Answer
# Pyth, 7 bytes

```
.n_McQ2

```

Try it online!

* `cQ2` chunks of evaluated input in length of 2
* `_M` maps over reversal in the chunk matrix
* `.n` flattens it
> 1 votes

# Answer
# Charcoal, 5 bytes

```
ＷＳ⟦Ｓι

```

Try it online! Link is to verbose version of code. Takes newline-terminated input. Explanation:

```
ＷＳ

```

Repeat while there is still input...

```
⟦Ｓι

```

... output the subsequent input before it.
> 1 votes

# Answer
# Pip `-rp`, 7 bytes

```
WVRVUWg

```

Try it online!

### Explanation

The flags are for input & output formatting: `-r` reads the program arguments from lines of stdin; `-p` formats the output as a list rather than concatenating it.

```
      g  List of arguments
    UW   Unweave into a pair of lists, each consisting of every other element
  RV     Reverse the order of those two lists
WV       Weave them back together

```
> 1 votes

# Answer
# Core Maude, 115 bytes

```
mod S is pr LIST{Nat}. op f : Nat ~> Nat . var A B : Nat . eq f(A B X:[Nat])=
B A f(X:[Nat]). eq f(nil)= nil . endm

```

The result is obtained by reducing the `f` function with the input list.

### Example Session

```
Maude> red f(1 2 3 4 5 6) .  --- Expected: 2 1 4 3 6 5
result NeList{Nat}: 2 1 4 3 6 5
Maude> red f(0 1 0 1) .  --- Expected: 1 0 1 0
result NeList{Nat}: 1 0 1 0

```

### Ungolfed

```
mod S is
    pr LIST{Nat} .

    op f : Nat ~> Nat .

    var A B : Nat .

    eq f(A B X:[Nat]) = B A f(X:[Nat]) .
    eq f(nil) = nil .
endm

```

Just the straightforward recursive solution. Saved a couple bytes by inlining the type in `X:[Nat]` rather than declaring it with the `var` keyword. Doing the same with `A` and `B` doesn't change the byte count — just the way the math works out.
> 1 votes

# Answer
# Icon, 47 bytes

```
procedure f(L)
L[i:=1to*L by 2]:=:L[i+1]&\z
end

```

Try it online!
> 1 votes

# Answer
# K (oK), 10 bytes

**Solution:**

```
,/|:'0N 2#

```

Try it online!

**Explanation:**

```
,/|:'0N 2# / the solution
     0N 2# / reshape into n x 2 grid
  |:'      / reverse (|:) each (')
,/         / flatten

```

**Alternatives:**

* `,/+|+0N 2#` \- also **10 bytes**
> 1 votes

# Answer
# Tcl, ~~49~~ 47 bytes

```
proc S L {lmap a\ b $L {lappend M $b $a}
set M}

```

Try it online!
> 1 votes

# Answer
# MMIX, 40 bytes (10 instrs)

Assumes 8-byte size for list elements.

`void __mmixware swao(uint64_t *l, size_t len)`

hexdump (jxd -T):

```
00000000: 42010009 3f010101 27010101 8fff0000  B¢¡µ?¢¢¢'¢¢¢Ɓ”¡¡
00000010: 8f020008 afff0008 af020000 e7000010  Ɓ£¡®Ḥ”¡®Ḥ£¡¡ḃ¡¡Ñ
00000020: 5b01fffa f8000000                    [¢”«ẏ¡¡¡

```

Disassembled:

```
swae    BZ   $1,1F          // if nothing, return
        SRU  $1,$1,1        // turn length into loop count
0H      SUBU $1,$1,1        // decrement loop count
        LDOU $255,$0,0      // load l[0]
        LDOU $2,$0,8        // load l[1]
        STOU $255,$0,8      // store the other way
        STOU $2,$0,0        // store the other way
        INCL $0,16          // l += 2
        PBNZ $1,0B          // if loop count isn't yet 0, loop back
1H      POP  0,0            // return

```
> 1 votes

# Answer
# Perl 5 \+ `-p`, 8 bytes

This sets `$_` (implicitly `print`ed by `-p`) to the next line of STDIN (`<>` \- which isn't trimmed via `chomp`) concatenated with the current line (`$_`).

```
$_=<>.$_
```

Try it online!

or (with `-nl -M5.10.0`):

```
say<>.$_
```

Try it online!

---

# Perl 5 \+ `-p -M5.10.0`, 8 bytes

This outputs (`say`) the next line of STDIN (`<>`), after converting to a number (`$-=`) to avoid the trailing newline, then the current line is output via `-p`.

```
say$-=<>
```

Try it online!
> 1 votes

# Answer
# Julia

## 25 bytes

```
!x=x[1:end.|>i->i-(-1)^i]
```

Attempt This Online!

## 24 bytes

```
!x=x[(I=1:end).-(-1).^I]

```
> 1 votes

# Answer
# ECMAScript 2015 with Lodash (Array), 39 bytes

```
l=>_.chunk(l,2).flatMap(s=>[s[1],s[0]])

```

Solution below works if array doesn't chunk evenly (`l.length % 2 == 1`)

```
l=>_.chunk(l,2).flatMap(s=>s.length-1?[s[1],s[0]]:s)

```
> 1 votes

# Answer
# Arturo, ~~37~~ 30 bytes

```
$=>[map&[a,b]->@[b,a]|flatten]

```

Try it
> 1 votes

# Answer
## Prolog - 36 bytes

```
s([],[]).s([A,B|L],[B,A|R]):-s(L,R).

```

Non code-golf:

```
;; swap empty list is empty list
swap([],[]).

;; swap of A,B followed by L is B,A followed by R, where swap(L,R).
swap([A,B|L],[B,A|R]):-swap(L,R).

```
> 1 votes

# Answer
# Python 3.8 (pre-release), 39 bytes

```
f=lambda x:x and[x.pop(~len(x)%2)]+f(x)

```

Try it online!
> 1 votes

# Answer
# Whitespace, 131 bytes

```

```

Attempt This Online!

Generated from the following asm2ws program:

```
2 / GETN / 2 / RCL / 2 / DIV
@LOOP
    DUP / BZ %END
    0 / GETN
    1 / GETN
    1 / RCL / PUTN
    32 / PUTC
    0 / RCL / PUTN
    32 /PUTC
    1 / SUB / B %LOOP
@END

```
> 1 votes

# Answer
# Vyxal, 16 bitsv2, 2 bytes

```
2ẇR

```

Try it Online!

Bitstring:

```
0100011100000110

```

another 2 byter
> 1 votes

# Answer
# Python 3, 48 bytes

```
f=lambda l:l[::-1][:2]+f(l[2:])if len(l)>1else l

```

Try it online!

Very simple. For some reason l\[:2:-1\] doesn't work.
> 1 votes

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


# Question
Title: Well that's odd... no wait, that's even!
# Preamble

Integers are always either even or odd. Even integers are divisible by two, odd integers are not.

When you add two integers you can infer whether the result will be even or odd based on whether the summands were even or odd:

* Even + Even = Even
* Even + Odd = Odd
* Odd + Even = Odd
* Odd + Odd = Even

Likewise, when you multiply two integers you can infer whether the result will be even or odd based on whether the factors were even or odd:

* Even * Even = Even
* Even * Odd = Even
* Odd * Even = Even
* Odd * Odd = Odd

Thus, if you know the evenness or oddness of all the variables in a math expression that only involves addition and multiplication, you can infer whether the result will be even or odd.

For example, we can confidently say that `(68 + 99) * 37` results in an odd because an even plus an odd (`68 + 99`) is an odd, and that odd times another odd (`odd * 37`) gives an odd.

# Challenge

Write a program or function that takes in a string only containing the four characters `eo+*`. This string represents a mathematical expression given in prefix notation involving only addition (`+`) and multiplication (`*`). Each `e` represents some arbitrary even number, and each `o` represents some arbitrary odd number.

Your task is to simplify the expression, printing or returning a single `e` or `o` based on whether the result of the expression is even or odd.

You can assume that the input will always be in valid prefix notation. Specifically, each `+` and `*` will always have two corresponding operands occurring after it. These operands may be a single `e` or `o`, or another `+` or `*` expression that in turn has operands.

For example, the input `*+eoo` could be read as `mul(add(e, o), o)`, or `(e + o) * o` in normal infix notation. The `e` and the first `o` are the operands corresponding to the `+`, and `+eo` and the last `o` are the operands corresponding to the `*`.

Just to make it clear, here are some invalid inputs that have incorrect prefix notation:

```
eo
ooe
o+e
ee*
+*oe
+e*o

```

A single trailing newline in the output is fine, but otherwise a plain `e` for even or `o` for odd is all that should be output.

**The shortest code in bytes wins.**

# Test Cases

(Empty lines are only to help visually separate similar cases.)

```
e -> e
o -> o

+ee -> e
+eo -> o
+oe -> o
+oo -> e
*ee -> e
*eo -> e
*oe -> e
*oo -> o

+e+ee -> e
+e+eo -> o
+e+oe -> o
+e+oo -> e
+e*ee -> e
+e*eo -> e
+e*oe -> e
+e*oo -> o

+o+ee -> o
+o+eo -> e
+o+oe -> e
+o+oo -> o
+o*ee -> o
+o*eo -> o
+o*oe -> o
+o*oo -> e

*e+ee -> e
*e+eo -> e
*e+oe -> e
*e+oo -> e
*e*ee -> e
*e*eo -> e
*e*oe -> e
*e*oo -> e

*o+ee -> e
*o+eo -> o
*o+oe -> o
*o+oo -> e
*o*ee -> e
*o*eo -> e
*o*oe -> e
*o*oo -> o

++eee -> e
++eeo -> o
++eoe -> o
++eoo -> e
++oee -> o
++oeo -> e
++ooe -> e
++ooo -> o

+*eee -> e
+*eeo -> o
+*eoe -> e
+*eoo -> o
+*oee -> e
+*oeo -> o
+*ooe -> o
+*ooo -> e

*+eee -> e
*+eeo -> e
*+eoe -> e
*+eoo -> o
*+oee -> e
*+oeo -> o
*+ooe -> e
*+ooo -> e

**eee -> e
**eeo -> e
**eoe -> e
**eoo -> e
**oee -> e
**oeo -> e
**ooe -> e
**ooo -> o

+e+e+e+ee -> e
+o+o+o+oo -> o
*e*e*e*ee -> e
*o*o*o*oo -> o
+e+o+e+oe -> e
+o+e+o+eo -> o
*e*o*e*oe -> e
*o*e*o*eo -> e
+e*e+e*ee -> e
+o*o+o*oo -> o
*e+e*e+ee -> e
*o+o*o+oo -> o

+**++*+*eeoeeooee -> e
+**++*+***eooeoeooeoe -> e
+**+***+**++**+eooeoeeoeeoeooeo -> o

+e*o*e**eoe -> e
+*e+e+o+e**eeoe -> e
**o++*ee*++eoe*eo+eoo -> o
```

# Answer
> 44 votes
## CJam, ~~18~~ ~~17~~ 13 bytes

*Thanks to aditsu for saving 4 bytes.*

```
qW:O%eu~"eo"=

```

Try the test suite here. (The test suite is too long for the permalink. Just copy them from the challenge spec.)

### Explanation

```
q     e# Read the input.
W:O   e# Push a -1 and store it in variable O.
%     e# Use the -1 to reverse the string, because CJam's stack-based nature and the
      e# commutativity of the operators means we can evaluate the code in postfix notation.
eu    e# Convert the string to upper case, turning 'e' into 'E' (a variable with even value
      e# 14) and 'o' into 'O' (which we've stored the odd value -1 in).
~     e# Evaluate the string as CJam code, leaving the result on the stack.
"eo"= e# Use the result as an index into the string "eo". CJam's indexing is cyclic so it
      e# automatically takes inputs modulo 2. Negative indices also work as expected.

```

# Answer
> 28 votes
# Pyth, ~~16~~ 14 bytes

```
@"eo".vjdXzGU9

```

Pyth can itself evaluate a string, that is in Pyth syntax. Therefore I replace `e` and `o` with `4` and `5`. Then the evaluation will give me an even or odd number, and I can easily print the result.

Try it online: Demonstration or Test Suite

### Explanation:

```
@"eo".vjdXzGU9   implicit: z = input string
         XzGU9   replace "e" in z with 4 and "o" with 5
       jd        put a space between each char
     .v          evaluate it (Pyth style)
@"eo"            and print "e" or "o"

```

Additional explanation to the replace. `G` is a variable initialized with the alphabet `abc...xyz`. `U9` is the list `[0, 1, ..., 8]`. `XzGU9` replaces the letters of the alphabet with the values of the list. So `a` gets replaced with `0`, `b` with `1`, ..., `e` with `4`, ..., `i` with `8`, `j` with `0`, ..., and `o` with `5`. Therefore I `e` gets replaced with an even number and `o` with an odd number. All the other replacements have no effect at all.

# Answer
> 17 votes
# Perl, ~~50~~ ~~45~~ 40 characters

(39 characters code + 1 character command line option.)

```
1while s/\+oe|\+eo|\*oo/o/||s/\W\w\w/e/

```

Sample run:

```
bash-4.3$ echo -n '**o++*ee*++eoe*eo+eoo' | perl -pe '1while s/\+oe|\+eo|\*oo/o/||s/\W\w\w/e/'
o

```

# Answer
> 13 votes
# Python 2, 90

```
def f(s):i=iter(s);a=next(i);return(a>'a')*a or'oe'[f(i)==f(i)if'*'<a else'e'in f(i)+f(i)]

```

The `iter` function is a good way to make the input string into a FIFO queue which remembers how much of the string has been parsed across calls of `f`. It is idempotent, so it is harmless to call it again when the input is already an iterator rather than a string. The trailing half of the answer beginning with `or'oe'`... seems like it should be golfable, but I couldn't find anything.

-1 thanks to Sp3000.

# Answer
> 13 votes
# Retina, 29 bytes

```
(+`\*oo|\+(eo|oe)
o
\W\w\w
e

```

For the convenient one file version the `-s` flag is used.

We swap odd expressions (`*oo`, `+oe`, `+eo`) to `o` until we can, then swap the remaining symbol-letter-letter expressions to `e`. We repeat this until we can and the final one letter is our output.

(This solution is similar to manatwork's Perl answer.)

Try it online! (by Dennis)

# Answer
> 10 votes
## Python 2, 80 bytes

```
def f(s,e=0,o=1):i=iter(s);a=next(i);return(a>'a')*a or'eo'[eval(f(i)+a+f(i))%2]

```

This is built on feersum's very clever answer that uses an `iter` to implement Polish-notation operations. The new idea is to use `eval` to evaluate the expressions `+` and `*` with `eval(f(i)+a+f(i))`, where the operator `a` is placed infix between the recursive results. The eval uses the bindings `e=0,o=1` in the optional function arguments. The output is then taken mod 2.

# Answer
> 9 votes
## Mathematica, ~~91~~ 84 bytes

```
#//.s_:>s~StringReplace~{"+ee"|"+oo"|"*ee"|"*eo"|"*oe"->"e","+eo"|"+oe"|"*oo"->"o"}&

```

Looking for a way to compress this...

# Answer
> 9 votes
## C, 79 bytes

Straightforward recursion. Relies on some (coincidental?) bitwise properties of the four allowed input characters.

```
f(){int c=getchar();return c&4?c:c&1?f()^f()^'e':f()&f();}main(){putchar(f());}

```

# Answer
> 8 votes
# Shell + GNU utilities, 33

```
dc -eFo`rev|tr oe OK`2%p|tr 10 oe

```

Input is taken from STDIN.

This does the same trick of reversing the input and evaluating with a stack-based calculator - in this case `dc`. We could replace `e` and `o` with `0` and `1`, but then spaces would need to be inserted to prevent greedy parsing of the digits into the incorrect numbers.

Instead `e` is replaced with `K` which is the `dc` command to push the current precision to the stack, which by default is 0. And `o` is replaced with `O` which is the `dc` command to push the current output base to the stack. This needs to be odd, so we set it to 15 with `Fo` before doing anything else in dc.

Then it is simply a matter of taking mod 2 and printing `2%p`. The only possible values are now `0` and `1`, so it doesn't matter that the output base is 15. Then `tr` translates back to `o` or `e`.

---

I like that if you squint your eyes, this source almost looks like `dc Forever OK`.

# Answer
> 6 votes
# Ruby, 61 bytes

Using recursive descent parsing and boolean algebra.

```
def f
gets(1)==?+?f^f : ~/\*/?f&f : $_==?o
end
puts f ? ?o:?e

```

The function reads one character from stdin at a time. If it reads a `+` or a `*`, it calls itself twice to determine odd or even. The function returns `true` for odd and `false` for `even`. The `^` *XOR* and `&` *AND* operators are used to determine "oddness" of addition and multiplication expressions respectively.

Here's an ungolfed version:

```
def f
  x = gets(1)
  case x
  when '+'
    f ^ f
  when '*'
    f & f
  else
    x == 'o'
  end
end

puts f ? 'o' : 'e'

```

Thanks @Shel for pointing out a bug in the initial version.

# Answer
> 5 votes
## Seriously, 24 bytes

```
,R'2'e(Æ'1'o(Æ£ƒ'e'o2(%I

```

More efficient stack manipulation could probably make this shorter, but meh, I'm happy with it.

Takes input as a string, like `"+*oee"`

Try it online (input must be manually entered)

Explanation:

```
,R        get input and reverse it
'2'e(Æ    replace all "e"s with "2"s
'1'o(Æ    replace all "o"s with "1"s
£ƒ        cast as function and call
'e'o2(%I  push "e" if result is even, else "o"

```

# Answer
> 5 votes
# Vyxal, 13 bytes

```
‛oe₀Ŀ∑ṘṄĖ₂∆ċt

```

Try it Online!

```
    Ŀ∑        # Replace each of
‛oe           # o and e
   ₀          # With 1 and 0
      Ṙ       # Reverse
       Ṅ      # Join by spaces
        Ė     # Eval
         ₂    # Even? (1-n%2)
          ∆ċt # Last character of num -> cardinal (one -> e, zero -> o)

```

# Answer
> 4 votes
## Minkolang 0.14, 40 bytes

I tried to do a clever eval method, but it turns out that any values added to the codebox outside of the original space will never be reached by the program counter. So I did a less clever eval method. :P

```
$o"eo+*"r0I4-[4g1Z2*1F]l*"e"+O.
0f1f+f*f

```

Try it here.

### Explanation

```
$o                                Read in whole input as characters
  "eo+*"                          Push these characters onto the stack (in reverse order)
        r                         Reverse the stack
         I4-                      Push the length of the stack - 4
            [                     For loop; pop n and repeat that many times
             4g                   Get the item at the fourth index and put it on top
               1Z                 Pops n and pushes first index of n in stack
                 2*               Multiply by 2
                   1F             Gosub; goes to codebox(2n,1) to be returned to
                     ]            Close for loop
                      l*          Multiply by 10
                        "e"+      Add 101 ("o" is 111)
                            O.    Output as character and stop.
0f1f+f*f                          Does the appropriate operation then returns to F

```

# Answer
> 4 votes
# JavaScript, 110 106 94 bytes

```
while(i.length>2)i=i.replace(/([+*][eo]{2})/,(o,e)=>{return"+oe+eo*oo".indexOf(o)<0?"e":"o"});

```

Certainly not the smallest solution, but likely the smallest solution possible in a verbose language like JavaScript!

# Answer
> 4 votes
# GNU Sed, 36

```
:
s/*oo\|+eo\|+oe/o/
t
s/\W\w\w/e/
t

```

After posting I saw this exactly the same approach as @manatwork's Perl answer and @randomra's Retina answer. So I guess I may as well go all the way and borrow their `\W\w\w` as well.

Thanks to @Ruud for shaving off 4 bytes.

# Answer
> 4 votes
# , ~~24~~ ~~20~~ ~~19~~ 18 bytes

```
i`2:e;1:o;~2%'o'e?

```

Takes input, reverses it, assigns `e` to *2* and `o` to *1* and ~~posts it to Tumblr~~ evaluates it as O code.

Explanation:

```
i`     Get input and reverse it, because O uses postfix notation
2:e;   Assign `e` to 2
1:o;   Assign `o` to 1
~2%    Eval and check if result is even
'o'e?  Output 'e' if even, 'o' if odd

```

# Answer
> 3 votes
# Haskell, 160 bytes

Call `f`.

```
f=until((==1).l)r
r s|l s<3=s|3#s?o=r('o':3%s)|3#s?sequence["+*","oe","oe"]=r('e':3%s)|0<1=1#s++r(1%s)
l=length
(#)=take
(%)=drop
(?)=elem
o=["+eo","+oe","*oo"]

```

# Answer
> 3 votes
## JavaScript, ~~92~~ 71 bytes

```
f=i=>i>"0"?i:f(i.replace(/.[eo]{2}/,e=>"eo"[eval((e[1]>"e")+"^&"[+(e[0]<"+")]+(e[2]>"e"))]))

```

It's a bit obfuscated, but I wanted to do something using `eval` and bitwise operators. Annotated:

```
f = (i) => // function(i) { return
    i>"0"  // i[0] == "o" || i[0] == "e" :-) - the characters `*` and `+` are both <"0"
      ? i  // finish
      : f(i.replace( // recursively repeat with
          /.[eo]{2}/, // first occurrence of "something" followed by two values
          (e) =>    // replaced by
              "eo"[ // string indexing
                eval(
                    (e[1]>"e")        // e[1] == "o" ? "true" : "false"
                  + "^&"[+(e[0]<"+")] // e[0] == "+" ? "^" : "&"
                  + (e[2]>"e")        // e[2] == "o" ? "true" : "false"
                )
              ]     // like eval(…) ? "o" : "e"
        ))

```

The repetition of `(e[…]>"e")` annoys me a bit, but the following is not better either (103 bytes):

```
f=i=>i>"0"?i:f(i.replace(/e|o/g,x=>+(x>"e")).replace(/.\d\d/,e=>"eo"[eval(e[1]+"^&"[+(e[0]<"+")]+e[2])]))

```

So in the end, @Arkain's approach with simple substring matching is superiour. Made into a function, with some optimisations:

```
f=i=>i>"0"?i:f(i.replace(/.[eo]{2}/,v=>"eo"[+"+oe+eo*oo".includes(v)]))

```

# Answer
> 2 votes
# Jolf, 11 bytes

(Noncompetitive, as the language postdates the question.) Try it here!

```
FVyAi"oe"@\x12

```

(Replace `\x12` with the actual character `\x12`. This should be done automatically in the interpreter.)

Explanation:

```
FVyAi"oe"@\x12
    i          input
          \x12 character 12
         @     char code at
   A "oe"      replace all os with 1s and all es with 2s
  y            eval as jolf, returning the answer
 V             return parity "even" or "odd"
F              get first character
               implicit output

```

# Answer
> 2 votes
## Haskell, 98 94 bytes

Sorry to bother you with yet another Haskell attempt; just wanted to prove it is very well possible in less than 100 bytes.

```
p(c:s)|any(<'a')s=p(c:p s)
p('+':x:y:s)|x/=y='o':s
p('*':'o':s)=s
p(c:_:_:s)|c<'a'='e':s
p s=s

```

Defines a function `p` that accepts any valid expression as parameter, and returns the result as a string of length 1.

Example:

```
*Main> p "**o++*ee*++eoe*eo+eoo"
"o"

```

The function works by repeatedly reducing the rightmost operator in the string until no operators are left.

# Answer
> 1 votes
# Dart, 173 bytes

```
f(i){var l=i.split(''),e='e',o='o';g(p){if(l[p]!=e&&l[p]!=o){var x=p+1,y=p+2;g(x);g(y);l[p]=l[p]=='+'?l[x]!=l[y]?o:e:l[x]==o?l[y]:e;l.removeRange(x,p+3);}}g(0);print(l[0]);}

```

This isn't competitive, but whatever. The gist of the solution is, starting at 0, recursively replace every operator with the evaluation the pair of characters following that operator and then remove those characters from the list.

# Answer
> 1 votes
# Haskell, 231 bytes

Here is an approach using a serious language ;)

Golfed version:

```
p(s:_)[]=s
p s(x:y)=p(r$x:s)y
r[]=[]
r('e':'e':'+':x)=r$'e':x
r('e':'o':'+':x)=r$'o':x
r('o':'e':'+':x)=r$'o':x
r('o':'o':'+':x)=r$'e':x
r('e':'e':'*':x)=r$'e':x
r('e':'o':'*':x)=r$'e':x
r('o':'e':'*':x)=r$'e':x
r('o':'o':'*':x)=r$'o':x
r x=x

```

Example:

```
*Main> p [] "+**+***+**++**+eooeoeeoeeoeooeo"
'o'

```

Ungolfed and pretty comprehensive version:

```
type Stack = String

parse :: String -> Char
parse = parse' []

parse' :: Stack -> String -> Char
parse' (s:_) []     = s
parse' s     (x:xs) = parse' (reduce $ x:s) xs

reduce :: Stack -> Stack
reduce [] = []
reduce ('e':'e':'+':xs) = reduce $ 'e':xs
reduce ('e':'o':'+':xs) = reduce $ 'o':xs
reduce ('o':'e':'+':xs) = reduce $ 'o':xs
reduce ('o':'o':'+':xs) = reduce $ 'e':xs
reduce ('e':'e':'*':xs) = reduce $ 'e':xs
reduce ('e':'o':'*':xs) = reduce $ 'e':xs
reduce ('o':'e':'*':xs) = reduce $ 'e':xs
reduce ('o':'o':'*':xs) = reduce $ 'o':xs
reduce xs               = xs

```

Example:

```
*Main> parse "+**+***+**++**+eooeoeeoeeoeooeo"
'o'

```

Features: Pattern matching and recursion.

# Answer
> 1 votes
# Python 3, ~~171~~ ~~145~~ 135 bytes

Not competitive, but I had fun doing it, so I just couldn't keep it to myself. Unlike the (very clever) recursive-iterator Python entry by feersum, this one reverses the input and then does a good old stack-based parsing of reverse Polish notation.

```
def p(i):
 s=[]
 for c in i[::-1]:
  s+=[c>'e'if c>'a'else getattr(s.pop(),'__'+('axnodr'[c>'*'::2])+'__')(s.pop())]
 return'eo'[s[0]]

```

# Answer
> 1 votes
# Add++, 46 bytes

```
D,g,@,d"oe"$eA"e"=+o
D,f,@,bR€gbU32CjbV2%"eo":

```

Try it online!

The footer simply enumerates all the example inputs and their corresponding outputs.

## How it works

Like a lost of the answers here, this uses replacement and evaluation. Our main function is `f`, and `g` is a helper function. We'll use `"*e*o*e*oe"` (which is `e`) as an example.

`f` begins by taking the input string and reversing it, yielding `"eo*e*o*e*"`. We then map `g` over each element:

`g` starts by duplicating the argument, to keep a copy until the final command. We then check if the argument is in the string `"oe"`, yielding **1** for letters and **0** for `*` or `+`. We then push the argument again and check whether it is equal to `"e"`. This result is then added to the previous check. This yields **0** for either `*` or `+`, **1** for `o` and **2** for `e`. We then take the logical OR between this value and the argument. If the value is **0**, it is replaced by the argument (i.e. `*` or `+`), otherwise it is left as-is (i.e. **1** and **2**).

This converts all letters in the reverse of the input into a numerical value. We then join each element by spaces, to ensure digits aren't concatenated. For our example, this yields the string `"2 1 * 2 * 1 * 2 *"`. We can then evaluate this, using Add++'s postfix notation, yielding **8**. We then take the parity of this value, yielding either **0** for even numbers and **1** for odd numbers, before indexing into the string `"eo"` and returning the corresponding letter.

# Answer
> 1 votes
# Lexurgy, 65 bytes

```
a propagate:
\+ {ee,oo}=>e
\+ {eo,oe}=>o
\* {eo,ee,oe}=>e
\*oo=>o

```

Explanation:

```
a propagate:     # while last output was not the same...
\+ {ee,oo}=>e    # handle even addition
\+ {eo,oe}=>o    # handle odd addition
\* {eo,ee,oe}=>e # handle even multiplication
\*oo=>o          # handle odd multiplication

```

As a bonus, if you copy-paste the test cases verbatim into Lexurgy, it will not touch the expected output side of the arrow.

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
„eoDIRs„¾X‡.Vè

```

Try it online or verify all test cases.

**Explanation:**

```
„eo            # Push string "eo"
   D           # Duplicate it
    IR         # Push the input, and reverse it
               # (since 05AB1E evaluates in Reverse Polish Notation)
      s        # Swap so one of the "eo" is at the top
       „¾X     # Push string "¾X"
               # (`¾` is 0 by default and `X` is 1 by default. We use these instead of
               # literals, because it could otherwise push 10, 100, "001", etc. instead
               # of loose digits)
          ‡    # Transliterate "e"→"¾" and "o"→"X"
           .V  # Pop, evaluate, and execute the string as 05AB1E code
             è # Index the resulting 0/1 into the "eo" string
               # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Thue, 95 bytes

```
*ee::=e
*eo::=e
*oe::=e
*oo::=o
+ee::=e
+eo::=o
+oe::=o
+oo::=e
>e::=~e
>o::=~o
i::=:::
::=
>i

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 66 bytes

```
f=a=>a>f?a:f(a.replace(/(\+oe|\+eo|\*oo)|.\w\w/,(v,c)=>c?'o':'e'))

```

Try it online!

From Bergi & Arkain's approach

# Answer
> 0 votes
# Python 3, 99 bytes

```
import re
a=b=input()
for i in a:a,b=re.subn(b and"\+(eo|oe)|\*oo"or"\W\w\w","oe"[b==0],a)
print(a)

```

Try it online!

Nice solution using regex. (python has already better solutions, go upote those)

# Answer
> 0 votes
# MathGolf, 23 bytes

```
x$╟⌠%_Z)m=9*m+$y~♂*♀)+$

```

Input as a list of characters to save a byte.

Try it online.

**Explanation:**

```
x                 # Reverse the (implicit) input-list
 $                # Convert each character to its codepoint-integer
  ╟⌠              # Push 62 (60+2)
    %             # Modulo
     _            # Duplicate the list
      Z)          # Push 39 (38+1)
        m=        # Check for each value if it's equal to 39 (1 if 39; 0 otherwise)
          9*      # Multiply each by 9
            m+    # Add the values in the lists together
              $   # Convert it from codepoint-integers back to characters
               y  # Join it together to a string
                ~ # Evaluate and execute it as MathGolf code
♂*                # Multiply each by 10
  ♀)              # Push 101 (100+1)
    +             # Add it to the integer
     $            # Convert it as code-point integer to character ('e' or 'o')
                  # (after which the entire stack is output implicitly)

```

Unfortunately MathGolf lacks a replace/transliterate builtin, otherwise this could be as easy as `xûoe2à`\<transliterate\>`~♂*♀)+$` (14 bytes).

# Answer
> 0 votes
# Swift 5.9, 99 bytes

```
let f={(i:inout _)in
for _ in""+i{i.replace(#/\W\w\w/#){"+oe+eo*oo".contains($0.output) ?"o":"e"}}}

```

Call it like this:

```
var string = "+**+***+**++**+eooeoeeoeeoeooeo"
f(&string)
print(string) // "o"

```

Here's a JDoodle link, with test cases. (Note that the tests will be output in a random order, since Swift dictionaries are unordered.)

---
Tags: code-golf, arithmetic, number-theory, parsing
---


title: Pretty Palintiples

text:
# Question
Title: Pretty Palintiples
Imagine you have a positive integer number \\$n\\$. Let \\$m\\$ be the number obtained by reversing \\$n\\$'s digits. If \\$m\\$ is a *whole* multiple of \\$n\\$, then \\$n\\$ is said to be a **reverse divisible number**. If neither are a **palindrome**, \\$m\\$ is called a **palintiple**.

For example, \\$1089 \cdot 9 = 9801\\$, so \\$9801\\$ is a **palintiple** because it is a whole multiple of its reversal, \\$1089\\$. Another example of a palintiple is \\$8712\\$, because \\$2178 \cdot 4 = 8712\\$.

It's easy to see that all **palindrome** numbers are reverse divisible, e.g. \\$171 \cdot 1 = 171\\$, so we're not interested in those, and we do not call them palintiples.

## Input

Your input is an integer \\$x\\$. You may assume \\$x \> 0\\$.

## Output

Your task is to print out the first \\$x\\$ **palintiple** numbers. You can format your output however you like as long as every element is clearly separated.

## Test Cases

```
Input      Output
x = 1      8712
x = 3      8712, 9801, 87912
x = 7      8712, 9801, 87912, 98901, 879912, 989901, 8799912

```

## Rules

This is , so shortest number of bytes wins.

# Answer
# Python 2, 61 bytes

```
m=9
while 1:
 m+=1;r=int(`m`[::-1])
 if m in(4*r,9*r):print m

```

A full program that prints indefinitely.

**Try it online!**

Why only multiples of four and nine? See the OEIS page and this linked reference by Dan Hoey.

---

If floating point errors are acceptable then (thanks to l4m2)...

### Python 3 57 bytes

```
m=9
while 1:m+=1;int(str(m)[::-1])in(m/4,m/9)and print(m)

```

**Try it online!** (The header just forces TIO to flush to stdout after each print, since it seems not to flush after the 60-second timeout.)
> 5 votes

# Answer
# JavaScript (V8), 61 bytes

A full program that prints the sequence indefinitely.

```
for(n=0;;n%r|r/n||print(n))r=[...++n+""].sort(_=>n%10).join``

```

Try it online!

### Commented

```
for(              // main loop:
  n = 0;          //   start with n = 0
  ;               //   loop forever
  n % r           //   do nothing if r is not a divisor of n
  | r / n         //   or r = n
  || print(n)     //   otherwise, print n
)                 //
  r =             //   compute r:
    [...++n + ""] //     increment n and turn it into a list of digits
    .sort(_ =>    //     reverse this list if and only if ...
      n % 10      //     ... n is not a multiple of 10
    ).join``      //     join back to a string

```
> 2 votes

# Answer
# Jelly, 9 bytes

```
ÆḌDUḌ€ċµ#

```

A full program that accepts a positive integer, \\$x\\$, from stdin and prints a Jelly representation of the first \\$x\\$ *palintiples*.

**Try it online!** \- N.B. it's very slow due to checking all proper divisors.

### How?

```
ÆḌDUḌ€ċµ# - Main Link: no arguments
       µ# - start with m=0 and count up, collecting the first {stdin} m for which:
ÆḌ        -   {m}'s proper divisors (excludes m itself, catering for
                                     the no-palindrome requirement)
  D       -   to decimal (vectorises)
   U      -   reverse each
    Ḍ€    -   convert each from decimal (each as vectorised form would take
                                         [] to 0 giving a false positive of m=0)
      ċ   -   count occurrences of {m}

```
> 2 votes

# Answer
# Haskell, 136 bytes

```
r 0 a=a
r n a=r(quot n 10)(a*10+mod n 10)
g n a|n<1=[]|mod a 10<1||r a 0==r(r a 0)0||mod a(r a 0)>0=g n(a+1)|1>0=a:g(n-1)(a+1)
f n=g n 1

```

Try it online!

My first Haskell golf, so it's probably not good lol
> 2 votes

# Answer
# Vyxal 3, 10 bytes

```
ЧṚ∦Ḋ≠gnt×Ẇ

```

Try it Online!

Does not check the factors of anything, probably will be golfable
> 2 votes

# Answer
# Vyxal, 65 bitsv2, 8.125 bytes

```
λKṫṘcnt*;ṅ

```

Try it Online!

Bitstring:

```
00000010010010001000001010000111001101101101011011101111111011011

```

Slow method checking factors, but I had to beat Jelly.
> 2 votes

# Answer
# Charcoal, 28 bytes

```
ＮθＷ‹ⅉθ«≦⊕φ¿∧﹪φχ∧⁻φ⮌φ¬﹪φ⮌φ⟦Ｉφ

```

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

```
Ｎθ

```

Input `x`.

```
Ｗ‹ⅉθ«

```

Repeat until `x` terms have been output.

```
≦⊕φ

```

Increment the variable `f` which is predefined to `1000`.

```
¿∧﹪φχ∧⁻φ⮌φ¬﹪φ⮌φ

```

Check whether `f` is not a multiple of `10` or a palindrome but is divisible by its reverse.

```
⟦Ｉφ

```

Output it on its own line if this is the case.

52 bytes for a fast version:

```
ＮθＦＥθ⍘⊕ι²Ｆ²⊞υ⁺ι✂⮌ικＦ01ＵＭυ⪫Ｅ⪪κι⁺μ⌊μιＩ…▷SΣＥ89××⁹⁹ＩιＩυθ

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
Ｎθ

```

Input `x`.

```
ＦＥθ⍘⊕ι²

```

Generate the binary numbers from `1` to `x`.

```
Ｆ²⊞υ⁺ι✂⮌ικ

```

Produce `2x` binary palindromes.

```
Ｆ01ＵＭυ⪫Ｅ⪪κι⁺μ⌊μι

```

Increase the run lengths of all of the runs by `1`.

```
Ｉ…▷SΣＥ89××⁹⁹ＩιＩυθ

```

Multiply each palindrome by both `792` and `891`, sort them into order, and output only the first `x`.
> 1 votes

# Answer
# Retina, 111 bytes

```
.+
*¶

$>:&*1
+`(1+)\1
${1}0
01
1
mL$w`^(.*)(?=.?$)
$%=$^$&
(.)\1*
$&$1
L$`.+
$.(792**)¶$.(891**
"$&,A`.+"^~)N`

```

Try it online! Explanation: In theory I could do this using unary division, but it would probably time out before producing any results at all, so I used the fact that all palintiples are either `792` or `891` times a palindromic string of `1`s and `0`s where no digit has a run length of `1`.

```
.+
*¶

$>:&*1

```

Generate the integers from `1` to `x+1` in unary.

```
+`(1+)\1
${1}0
01
1

```

Convert them to binary.

```
mL$w`^(.*)(?=.?$)
$%=$^$&

```

Produce `2x+2` binary palindromes.

```
(.)\1*
$&$1

```

Increase the run length of all the runs by `1`.

```
L$`.+
$.(792**)¶$.(891**

```

Multiply each palindrome by both `792` and `891`.

```
N`

```

Sort them in numeric order.

```
"$&,A`.+"^~)`

```

Keep only the first `x`.
> 1 votes

# Answer
# Perl 5, 40 bytes

```
$_%($;=reverse)|/^$;$|0$/||say while++$_

```

Try it online!

Outputs the sequence indefinitely.
> 1 votes

# Answer
# Raku (Perl 6) (rakudo), 48 bytes

```
(1..*).grep({$_%10&&$_!=.flip&&$_%%.flip})».say

```

(Continues indefinitely, printing out all the palintiples it finds.)

Attempt This Online!
> 1 votes

# Answer
# Uiua 0.10.0, 32 30 bytes SBCS

```
⍥(+1⟨◌|&p⟩↧±◿10,>⊃◿≠⍜°⋕⇌...)∞0

```

Try on Uiua Pad!

Prints indefinitely.

```
0        # starting at 0
⍥(       # repeat
  ...    # dup input 3 times on stack
  ⍜°⋕⇌   # stringify, reverse, then parse
  >⊃◿≠   # m = 0 mod n AND m != n
  ±◿10,  # test 10 does not divide m
  ↧      # AND results
  ⟨◌|&p⟩ # print if true
  +1     # add 1 to m
)∞       # until fixed point (never)

```
> 1 votes

# Answer
# Scala 3, 84 bytes

```
var m=9;while(1<2){m+=1;val r=m.toString.reverse.toInt;if(m==4*r||m==9*r)println(m)}

```

Attempt This Online!
> 1 votes

# Answer
# Uiua, 23 bytes SBCS

Try on Uiua Pad!

Prints indefinitely.

```
⍥(+1⍥⟜&p∊:×4_9⍜°⋕⇌..)∞1

```

Explain:

```
              ⍜°⋕⇌.     # generate palindrome from input
        ∊:×4_9     .    # if the 4*palindrome or 9*palindrome
    ⍥⟜&p                # print if true
  +1                    # increment
⍥(                  )∞1 # repeat forever, starting at 1

```
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
µNÑ¨íNåD–

```

Try it online.

**Explanation:**

```
µ         # Loop while the counter variable (default 0) is not equal to the (implicit)
          # input-integer:
 N        #  Push the current loop-index
  Ñ       #  Pop and push a list of its divisors
   ¨      #  Remove the number itself (for palindrome cases)
    í     #  Reverse each divisor in the list
     Nå   #  Pop and check if the loop-index itself is in the list of reversed divisors
       D  #  Duplicate this check
        – #  Pop, and if it's truthy: print the loop-index with trailing newline
          #  Pop, and if it's truthy: implicitly increase the counter variable by 1

```
> 1 votes

# Answer
# Racket, 223 bytes

```
(define(r n a)(if(= n 0)a(r(quotient n 10)(+(* a 10)(modulo n 10)))))
(define(f x #:a[a 1])(if(= x 0)'()(if(and(>(modulo a 10)0)(not(=(r a 0)(r(r a 0)0)))(=(modulo a(r a 0))0))(cons a(f(- x 1)#:a(+ a 1)))(f x #:a(+ a 1)))))

```

Try it online!

Disclaimer: I'm not exactly good at golfing in Racket.
> 0 votes

# Answer
# PowerShell Core, 82 bytes

```
for(){if((++$i%10)*($i-ne($u=-join("$i"|% t*y|%{"$i"[-++$t]})))*!($i%$u)){$i}$t=0}

```

Try it online!

Prints all the palintiple, separated by newlines
> 0 votes

---
Tags: code-golf, number, sequence, number-theory, palindrome
---


title: Lattice points visible from the origin

text:
# Question
Title: Lattice points visible from the origin
# Challenge

Create a program that outputs a square grid showing *visible* and *non-visible* points \\$(x, y)\\$ from the origin based on their greatest common divisor (GCD).

A point \\$(x, y)\\$ is considered *visible* from the origin \\$(0, 0)\\$ if the \\$\gcd(x, y) = 1\\$. Otherwise, it's *non-visible*.

**Input**

An integer \\$n\\$, representing the radius of the square grid from the origin along both \\$x\\$ and \\$y\\$ axes.

**Output**

A square grid centered at the origin, where each cell is:

* ". " (dot followed by a space) for a *visible* point
* "\\$\ \ \\$" (two spaces) for a *non-visible* point

# Examples

Length from the origin: **n = 6**

```
  .       .   .       .
.   . . . .   . . . .   .
  .   .   .   .   .   .
  . .   . .   . .   . .
  .   .   .   .   .   .
. . . . . . . . . . . . .
          .   .
. . . . . . . . . . . . .
  .   .   .   .   .   .
  . .   . .   . .   . .
  .   .   .   .   .   .
.   . . . .   . . . .   .
  .       .   .       .

```

Length from the origin: **n = 5**

```
  . . . .   . . . .
.   .   .   .   .   .
. .   . .   . .   . .
.   .   .   .   .   .
. . . . . . . . . . .
        .   .
. . . . . . . . . . .
.   .   .   .   .   .
. .   . .   . .   . .
.   .   .   .   .   .
  . . . .   . . . .

```

Length from the origin: **n = 4**

```
  .   .   .   .
.   . .   . .   .
  .   .   .   .
. . . . . . . . .
      .   .
. . . . . . . . .
  .   .   .   .
.   . .   . .   .
  .   .   .   .

```

Length from the origin: **n = 3**

```
  . .   . .
.   .   .   .
. . . . . . .
    .   .
. . . . . . .
.   .   .   .
  . .   . .

```

Length from the origin: **n = 2**

```
  .   .
. . . . .
  .   .
. . . . .
  .   .

```

Length from the origin: **n = 1**

```
. . .
.   .
. . .

```

# References

Visible Points in a Lattice

Visible Point -- from Wolfram MathWorld

Lattice points visible from the origin

# Answer
> 6 votes
# Jelly, 12 bytes

```
rNgþ`=1ị⁾. G

```

Try It Online!

-3 bytes thanks to totallyhuman (-1 myself on top of this)

### Explanation

```
rNgþ`=1ị⁾. G    Main Link
rN              [n, ..., -n]
  gþ`           Outer product table over GCD
     =1         Check if equal to 1 (vectorizes)
       ị⁾. G    Index into [".", " "] and display as grid

```

# Answer
> 3 votes
# Haskell, ~~68~~ 61 bytes

*-7 bytes thanks to Lynn.*

```
f n|r<-[-n..n]=unlines[do x<-r;" . "!!min(gcd x y)2:" "|y<-r]

```

Try it online!

`unlines` can be dropped if a list of lines is okay.

# Answer
> 2 votes
# APL (Dyalog Unicode), 30 bytes SBCS

Assume `⎕io←0`

```
{↑,⌿'. ' '  '[1≠∘.∨⍨⍵-⍳1+⍵+⍵]}

```

Try it on APLgolf!

```
{↑,⌿'. ' '  '[1≠∘.∨⍨⍵-⍳1+⍵+⍵]}
                    ⍵-⍳1+⍵+⍵   ⍝ indices ⍵ ⍵-1 ⍵-2 ... 2-⍵ 1-⍵ -⍵
                ∘.∨⍨           ⍝ pairwise GCD
              1≠               ⍝ is not 1
    '. ' '  '[              ]  ⍝ Choose between strings '. ' and '  '.
 ↑,⌿                           ⍝ Combine the strings

```

# Answer
> 2 votes
# JavaScript (V8), 89 bytes

```
n=>{for(y=~n;y++-n;)print((g=(a,b=y)=>x-~n?b?g(b,a%b):(a*a-1?"  ":". ")+g(--x):"")(x=n))}

```

Try it online!

### Commented

```
n => {                  // n = input
  for(                  // main loop:
    y = ~n;             //   start with y = -n - 1
    y++ - n;            //   stop when y = n / increment y afterwards
  )                     //
  print(                // print the next line:
    ( g = (             //   g is a recursive function taking:
        a,              //     an integer a
        b = y           //     and an integer b initialized to y
      ) =>              //
      x - ~n ?          //   if x is greater than -n - 1:
        b ?             //     if b is not 0:
          g(b, a % b)   //       do a recursive call with [a, b] = [b, a mod b]
        :               //     else:
          ( a * a - 1 ? //       if a² is not equal to 1:
              "  "      //         append two spaces
            :           //       else:
              ". "      //         append a period and a space
          ) + g(--x)    //       decrement x and do a recursive call
      :                 //   else:
        ""              //     stop
    )(x = n)            //   initial call to g with a = x = n
  )                     // end of print()
}                       //

```

# Answer
> 2 votes
# Ruby, ~~74~~ 51 bytes

-23 (!) bytes thanks to Sisyphus

```
->n{a=-n..n
a.map{|y|a.map{" ."[2[_1.gcd y]]+" "}}}

```

Attempt This Online!

# Answer
> 2 votes
# C (gcc), 107 bytes

*-8 bytes, thanks to ceilingcat*

```
g(a,b){return b?g(b,a%b):a*a;}x,y;f(l){for(y=~l;y++<l;puts(""))for(x=~l;x++<l;)printf(g(x,y)-1?"  ":". ");}

```

Try it online!

# Answer
> 2 votes
# Python+Numpy+Pandas, 152 bytes

```
import numpy as np,pandas
def p(n):pandas.DataFrame([c for c in np.dstack(np.mgrid[-n:n+1,-n:n+1]).reshape(-1,2)if np.gcd(*c)==1]).plot.scatter(x=0,y=1)

```

Outputs a graphical plot (even though this isn't strictly the challenge, but when do you see Pandas in code golf?). Ex, `p(3)`:

# Answer
> 1 votes
# Charcoal, 33 bytes

```
Ｅ⊕Ｎ⭆⊕ι§ .∧∨ιλ⬤…²⊕ι∨﹪ιν﹪λν‖Ｏ↗↑←ＵＥ¹

```

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

```
Ｅ⊕Ｎ⭆⊕ι§ .∧∨ιλ⬤…²⊕ι∨﹪ιν﹪λν

```

Draw one octant of the diagram.

```
‖Ｏ↗↑←

```

Reflect to complete the diagram. (The reflections are performed serially, so first the octant is reflected diagonally to create the quadrant, then the other two reflections complete the negative axes.)

```
ＵＥ¹

```

Space the `.`s horizontally.

# Answer
> 1 votes
## Pascal, 238 Bytes

This is a complete `program` as per ISO standard 7185 “Standard Pascal”.

```
program p(input,output);type Z=integer;var n,y:Z;function f(a,b:Z):Z;begin f:=a;if b>0 then f:=f(b,a mod b)end;begin read(n);n:=abs(n);for y:=-n to n do begin for n:=-n to n do write((' .')[ord(f(abs(n),abs(y))=1)+1],' ');writeLn end end.

```

Ungölfed:

```
program latticePointsVisibleFromOrigin(input, output);
    const
        mark = ' .';
    type
        Z = integer;
    var
        n, y: Z;
    { GreatestCommonDivisor for _nonnegative_ _integers_ _only_. }
    function greatestCommonDivisor(a, b: Z): Z;
        begin
            greatestCommonDivisor ≔ a;
            if b > 0 then
            begin
                greatestCommonDivisor ≔ greatestCommonDivisor(b, a mod b)
            end
        end;
    { ─── main ────────────────────────────────────────────────── }
    begin
        readLn(input, n);
        n ≔ abs(n);

        { In Pascal `for`‑loop limits are evaluated (exactly) once. }
        for y ≔ n downto −n do
        begin
            for n ≔ −n to n do
            begin
                { `+1` because in Pascal `string` indices are one‑based. }
                write(output,
                    mark[ord(greatestCommonDivisor(abs(n), abs(y)) = 1) + 1],
                    ' ')
            end;
            writeLn(output)
        end
    end.

```

# Answer
> 1 votes
# Scala 3, 148 bytes

A port of @Jordan's Ruby answer in Scala.

---

Golfed version. Attempt This Online!

```
n=>{val a=(-n to n);(for(x<-a;y<-a)yield(x,y)).map{case(x,y)=>if(BigInt(x).gcd(y)==1)". " else"  "}.grouped(n*2+1).foreach(r=> println(r.mkString))}

```

Ungolfed version. Attempt This Online!

```
object Main extends App {
  def F(n: Int): Unit = {
    val a = (-n to n).toList
    val pairs = for (x <- a; y <- a) yield (x, y)
    val pattern = pairs.map { case (x, y) => if (BigInt(x).gcd(y) == 1) ". " else "  " }
    pattern.grouped(n * 2 + 1).foreach(row => println(row.mkString))
  }

  F(6)
}

```

# Answer
> 1 votes
# PARI/GP, 64 bytes

```
n->[print(concat([if(gcd(i,j)-1,"  ",". ")|j<-r]))|i<-r=[-n..n]]

```

Attempt This Online!

# Answer
> 1 votes
# TI-Basic, 65 bytes

```
Input N
For(I,~N,N
".
For(J,~N,N
Ans+sub(" .",1=gcd(abs(I),abs(J)),1)+"
End
Disp sub(Ans,2,2N+1
End

```

`~` represents the negative sign. The fifth line ends with a space. The output may be cut off if the input is too large.

# Answer
> 1 votes
# Uiua SBCS, 31 bytes

```
⊏:" ."=1◌⊞⍢⊃◿∘±:↘1♭≡⊂0.⌵-⇡+1×2.

```

Try it!

```
⊏:" ."=1◌⊞⍢⊃◿∘±:↘1♭≡⊂0.⌵-⇡+1×2.
                        -⇡+1×2.  # [-n..n]
                       ⌵         # abs
                      .          # duplicate
               :↘1♭≡⊂0           # interleave zeros
         ⊞⍢⊃◿∘±                  # table by gcd
        ◌                        # pop
      =1                         # where is it equal to one?
⊏:" ."                           # change to string

```

# Answer
> 1 votes
# 05AB1E, 13 bytes

```
(ŸÄDδ¿Θ»T„. ‡

```

Try it online or verify all test cases.

**Explanation:**

```
(              # Negate the (implicit) input-integer
 Ÿ             # Push a list in the range [(implicit) input, -input]
  Ä            # Take the absolute value of each: [n,n-1,...,0,...,n-1,n]
   Dδ¿         # Create a GCD-table of this list:
   D           #  Duplicate the list:
    δ          #  Pop both lists, and apply double-vectorized:
     ¿         #   Greatest Common Divisor
      Θ        # Check which values are 1 (1 if 1; 0 otherwise)
       »       # Join each inner list by spaces, and then each string by newlines
        T      # Push 10
         „.    # Push ". "
            ‡  # Transliterate all 1s to "."s and all 0s to spaces
               # (after which the result is output implicitly)

```

---
Tags: code-golf, math, ascii-art
---


# Question
Title: Scan input for numbers and add thousands separators
# Challenge

Given ASCII-encoded text input of any size, detect numbers between -1,000,000,000,000,000,000 and 1,000,000,000,000,000,000 exclusive and rewrite them with thousands separators. Use commas only and ignore leading zeroes. Leave the rest of the input unchanged.

# Test cases

| Input | Output | Description |
| --- | --- | --- |
| `123` | `123` |  |
| `1234` | `1,234` |  |
| `-12345` | `-12,345` |  |
| `x12345y` | `x12,345y` | ignore surrounding characters |
| `1234 xyz 56789` | `1,234 xyz 56,789` |  |
| `1234,56789` | `1,234,56,789` | 1,234 and 56,789 are separate numbers |
| `0001234` | `0001,234` | zeroes are not part of the number |
| `10000000` | `10,000,000` | only leading zeroes are ignored |
| `1234567891234567890` | `1234567891234567890` | 1,234,567,891,234,567,890 is outside the range |
| `0123456789123456789` | `0123,456,789,123,456,789` |  |

---

Standard loopholes apply. Shortest code in bytes wins.

# Answer
> 6 votes
# Perl 5 `-p`, ~~58~~ 50 bytes

```
s%[1-9]\d*%$&<1E18?$&=~s/.\K(?=(...)+$)/,/gr:$&%ge

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 66 bytes

*-3 thanks to @tsh*

```
s=>s.replace(/0|\d+/g,s=>s[18]?s:s.replace(/.(?=(...)+$)/g,"$&,"))

```

Try it online!

### Commented

```
s =>                   // s = input string
s.replace(             // replace in s:
  /0|\d+/g,            //   we define a number as either a single zero
                       //   or a sequence of digits without leading zeros
  s =>                 //   for each such number s,
  s[18] ?              //   if it's longer than 18 characters:
    s                  //     leave it unchanged
  :                    //   else:
    s.replace(         //     replace in s:
      /.(?=(...)+$)/g, //       each digit followed by one or several groups of
                       //       3 digits covering exactly the end of the string
      "$&,"            //       with the same digit followed by a comma
    )                  //     end of replace()
)                      // end of replace()

```

# Answer
> 3 votes
# Python 3, ~~88~~ 85 bytes

*-3 bytes thanks to movatica.*

```
lambda s:re.sub('[1-9]\d*',lambda n:len(a:=n[0])<19and f'{int(a):,}'or a,s)
import re

```

Try it online!

Right tool for the job.

## More regex-y solution, ~~93~~ 92 bytes

*-2 bytes thanks to ovs. Another one bytes the dust thanks to movatica.*

```
lambda s:re.sub('(^0*|\D0*)([1-9]\d{,17})(?!\d)',lambda n:n[1]+f'{int(n[2]):,}',s)
import re

```

Try it online!

Tries to check for the length restriction within the regex, but I'm not very good at regex so it could probably be better. :P

# Answer
> 3 votes
# Retina 0.8.2, 52 bytes

```
r`(?<=[1-9]0*)\d{3}(?(?=\d)\G|(?<![1-9]\d{18,}))
,$&

```

Try it online! Link includes test cases. Explanation:

```
r`

```

Use right-to-left matching. In particular, this starts matching from the end of the string and works back to the start. This is important for the `\G` reference, which effectively now matches the start of the next match rather than the end of the previous match.

```
(?<=[1-9]0*)

```

Each set of three digits must be preceded by at least one nonzero digit.

```
\d{3}

```

Match three digits.

```
(?(?=\d)\G|(?<![1-9]\d{18,}))

```

If the next character is also a digit, then the matches need to be contiguous, otherwise there must not be a non-zero digit at least 18 digits away.

```
,$&

```

Precede the three digits with a comma.

# Answer
> 3 votes
# Scala 3, 90 bytes

Thanks for @movatica for code improvement.

In golfed version, `scala.util.matching.Regex` is imported implicitly.

---

Golfed version. Attempt This Online!

```
s=>"[1-9]\\d*".r.replaceAllIn(s,m=>{val x=m.matched;if(x.size<19)f"${x.toLong}%,d"else x})

```

Ungolfed version. Attempt This Online!

```
import scala.util.matching.Regex

object Main {
  def main(args: Array[String]): Unit = {
    val tests = List(
      "123",
      "1234",
      "-12345",
      "x12345y",
      "1234 xyz 56789",
      "1234,56789",
      "0001234",
      "10000000",
      "1234567891234567890",
      "0123456789123456789"
    )

    tests.foreach(t => println(replaceNumbers(t)))
  }

  val replaceNumbers: (String => String) = s =>
    "[1-9]\\d*".r.replaceAllIn(
      s,
      m => if (m.matched.size < 19) f"${m.matched.toLong}%,d" else m.matched
    )
}

```

# Answer
> 3 votes
# JavaScript (Node.js), 60 bytes

```
f=s=>s.replace(/0|(\d+)(\d{3})/g,(_,a,b)=>a<1e15?[f(a),b]:_)

```

Try it online!

```
f=s=>                 // Will recurse
s.replace(            // Replace
  /0|(\d+)(\d{3})/g,  // Leading zero treated as a single part
                      // which would also convert to 0
  (_,a,b)=>           // (matched, matched[:-3], matched[-3:]
    a<1e15?           // If matched < 1e18, then a < 1e15
                      // Also 1e15 is smaller than MAX_SAFE_INTEGER
                      // so no error would occur
      [f(a),b]        // matched[-3:] is a group
    :                 // Notice that matched[:-3] also work as a part
      _               // If matched >= 1e18 or matched is undefined
                      // aka. matching a single 0,
)                     // then return as-is.

```

Looks portable to other languages.

# Answer
> 1 votes
# Python 3.8 (pre-release), 112 bytes

```
f=lambda s,x=1:s and(s[':'>s>'1':1]or f'{int(s[:(x:=[*map(str.isdigit,s),0].index(0))]):{","[:x<19]}}')+f(s[x:])

```

Try it online!

Wrong tool for the job (but sans regex)

-15 thanks to totallyhuman

# Answer
> 1 votes
# Charcoal, ~~42~~ 40 bytes

```
Ｆ⊞Ｏ⪪Ｓ¹ω¿№ＩΦχ∨υλι⊞υι«⮌⪫⪪⮌⪫υω³…,‹Ｌυ¹⁹≔⟦⟧υι

```

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

```
Ｆ⊞Ｏ⪪Ｓ¹ω

```

Split the input into characters, append the empty string to the list, then loop over them.

```
¿№ＩΦχ∨υλι

```

Test whether the current character is a digit from `0-9` or `1-9` depending on whether any digits have been collected yet.

```
⊞υι

```

If it is a collectable digit then collect it.

```
«

```

Otherwise:

```
⮌⪫⪪⮌⪫υω³…,‹Ｌυ¹⁹

```

Reverse the digits, regroup them into strings of three characters, join them with commas if there are fewer than 19, and reverse the result.

```
≔⟦⟧υ

```

Clear the list of digits.

```
ι

```

Output the current "non-digit" (could be `0` if we're not collecting digits yet).

# Answer
> 1 votes
# Uiua SBCS, 51 bytes

```
⍜⊜□⍚(⟨◌|/◇⊂↘1♭≡⊂@,⊜□⇌\+=0◿3⇡⟩<19.⧻.)↧\+≠@0⟜∊,+@0⇡10

```

Try it!

```
⍜⊜□⍚(⟨◌|/◇⊂↘1♭≡⊂@,⊜□⇌\+=0◿3⇡⟩<19.⧻.)↧\+≠@0⟜∊,+@0⇡10
                                             +@0⇡10  # the digits
                                           ∊,        # mask of locations
                                     \+≠@0⟜          # mask of non-leading zeros
                                    ↧                # combine
⍜⊜□⍚(                              )                 # map over mask groups
     ⟨◌|                    ⟩<19.⧻.                  # only process if < 19 digits
                     \+=0◿3⇡                         # mask of triplet groups
                    ⇌                                # reverse
                  ⊜□                                 # split
           ↘1♭≡⊂@,                                   # put comma between each triplet
        /◇⊂                                          # join

```

# Answer
> 1 votes
# Pip, 31 bytes

```
aR`[1-9]\d+`{#a<19?R:Ra<>3J',a}

```

Attempt This Online!

### Explanation

```
aR`[1-9]\d+`{#a<19?R:Ra<>3J',a}
aR                               ; In command-line argument, replace
  `[1-9]\d+`                     ; 1-9 followed by more digits
            {                 }  ; with the following callback function:
             #a<19?              ;  If the length of the match is less than 19 digits:
                     Ra          ;   Reverse the match
                       <>3       ;   Group into substrings of length 3
                          J',    ;   Join on comma
                   R:            ;   Reverse back
                             a   ;  Otherwise, return the match unchanged

```

Created with the help of Luminespire.

The double-reversal is necessary because `<>` groups from the left; for example, `1234<>3 == [123;4]`.

# Answer
> 1 votes
# Vyxal 3 `d`, 28 bytes

```
ᵛK¯0Jƒ“ƛ⌊[ᶤ⌊∦ΘİfƛL19<[Ṛ⁻',jṚ

```

Try it Online!

no regex needed

```
ᵛK¯0Jƒ“ƛ⌊[ᶤ⌊∦ΘİfƛL19<[Ṛ⁻',jṚ
ᵛK                            # is each character numeric
  ¯0J                         # pairwise differences with a zero appended
     ƒ“                       # split after truthy indices and concatenate sublists
# This splits the string on numbers
       ƛ                      # map over each group
        ⌊[                    # if it is a non-zero number
          ᶤ⌊∦Θİf              # slice at the first non-zero index
                ƛ             # map over each new group
                 L19<[        # if the length is less than 19
                      Ṛ⁻      # reverse and split into triplets
                        ',jṚ  # join by commas and reverse
# d flag concatenates until no sublists remain

```

Created with the help of Luminespire.

# Vyxal `d`, 25 bytes

```
⁽±Ḋƛ±[⁽⌊Ǒ₍ẎȯƛL19<[Ṙ3ẇ\,jṘ

```

Try it Online! vyxal 2 port

# Answer
> 1 votes
# 05AB1E, 30 bytes

```
.γd}εDdiïDg19‹iR3ô',ýRyγн0Ãì]J

```

Try it online.

**Explanation:**

```
.γ                     # Group the characters of the (implicit) input-string by:
  d                    #  Check whether its a non-negative number (aka a digit)
   }ε                  # After the group-by: Map over each group:
     D                 #  Duplicate it
      di               #  If this is a group of digits:
        ï              #   Remove leading 0s by casting it to an integer
         D             #   Duplicate it
          g19‹i        #   If its length is smaller than 19:
               R       #    Reverse it
                3ô     #    Split it into triplets
                  ',ý '#    Join it with "," delimiter
                     R #    Reverse it back
               y       #    Push the current group's string of digits
                γ      #    Split it into equal adjacent groups
                 н     #    Leave only the first group
                  0Ã   #    Leave only the 0s in this group
                    ì  #    Prepend this string (either "" or 0s) to the string
                       #   (implicit) else: use the duplicated integer that's too large
                       #  (implicit) else: use the duplicated non-digit group
    ]                  # Close both the nested if-statements and map
     J                 # Join all groups back together
                       # (after which the result is output implicitly)

```

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


title: Avoiding Loops!

text:
# Question
Title: Avoiding Loops!
Given a collection of coloured laces, what would be the probability, \\$P\\$, that Alice won't create any loops if, until impossible, they tie two uniformly chosen, free lace ends of differing colours together?

For the avoidance of doubt:

* Each lace will be of only one colour and will have precisely two ends.
* Alice does not *choose* lace ends, rather they are selected by a random process such that each pair of free lace ends with differing colours is equally likely.
* Once Alice has tied two lace ends together they become unavailable (i.e. they are no longer "free lace ends").
* If, at any point, there are no pairs of free lace ends of differing colours and no loops, Alice is done and has successfully avoided creating any loops.

### I/O:

**Input:** Any reasonable representation of the collection of laces.

Some suggestions (the examples in this section are for a collection of six laces, one red, two green, and three blue):

* A list of colour counts (as used in the *Examples* and *Tests* sections)
(`[1, 2, 3]`)
* A list of lace colours as numbers or strings
(`["red", "green", "green", "blue", "blue", "blue"]`)
* A list of laces as pairs of equal numbers or strings
(`[("red", "red"), ("green", "green"), ("green", "green"), ("blue", "blue"), ("blue", "blue"), ("blue", "blue")]`)
* A list of lace ends as lace colour, lace identifier pairs
(`[("red", 1), ("red", 1), ("green", 2), ("green", 2), ("green", 3), ("green", 3), ("blue", 4), ("blue", 4), ("blue", 5), ("blue", 5), ("blue", 6), ("blue", 6)]`)

The input may be assumed to be pre-sorted in any order.

**Output:** The probability of making no loops.

* This may be a numerator, denominator pair (in either, specified order), a fraction object, a floating point number, etc.
* Type or machine inaccuracies are acceptable as long as the method is fundamentally sound but if these do adversely affect the test case results then do try to provide an alternative without inaccuracies.
* This is , so you may not approximate the result by sampling (but do feel free to enumerate all possibilities).

### Scoring

This is , so try to minimise the bytes of code in your language of choice.

### Examples

*Using colour counts, sorted ascending...*

**`[2]`** (e.g. two blue laces)
No lace ends can be tied together since all four are of the same colour, thus no loop may be made, so \\$P = 1\\$.

**`[1, 1]`** (e.g. one black lace and one white lace)
All four initial choices of pairs of lace ends of differing colours produce a single string of the two laces, with ends of different colours. At this point, the only option is to tie the two remaining lace ends together forming a loop and thus \\$P=0\\$.

**`[1, 2]`** (e.g. one red lace and two green laces)
The only available first move is to tie one end of the unique lace to one end of either of the other two laces, after which we'll be left with a string of two differently coloured laces along with a lone lace of the more common colour. At this point, one of the two ends we pick must be the remaining end of the unique lace, which is on the string, and the other must be one of the three remaining ends of the other colour. One of these lace ends is on the other end of the string and would form a loop, while the other two lace ends will result in a single string formed of all three laces with the unique lace in the middle whereupon no loop may be formed and thus \\$P=\frac{2}{3}\\$.

**`[1,4]`** (e.g. one pink lace and four yellow laces)
This follows much the same logic as `[1,2]`. We must first form a string from the unique lace and another. Then we only form a loop if we pair the remaining uniquely coloured lace end with the other end of the string it is on otherwise we pair with one of the other six lace ends and create a string of three laces with the unique lace in the middle at which point all available lace ends will be of one colour, so \\$P=\frac{6}{7}\\$.

**`[2,3]`** (e.g two orange laces and three purple laces)

Rather than even more words, the below starts with `OO OO PP PP PP` and enumerates the next possible states, with `L` for a loop and strings represented as their two free lace ends (enumeration stops whenever a loop is formed, and equivalent states at any step have been collapsed):

```
      OO OO PP PP PP

   1) OP OO PP PP  (24/24)...

  1A) OO PP PP     (6/15)...
  1B) OP OP PP     (8/15)...
  1C) L OO PP PP   (1/15) loop

 1A1) OP PP        (8/8)...

 1B1) OP PP        (6/8)...
 1B2) L OP PP      (2/8) loop

1A1A) PP           (2/3) no loop
1A1B) L PP         (1/3) loop

1B1A) PP           (2/3) no loop
1B1B) L PP         (1/3) loop

P = P(1A1A) + P(1B1A)

```

...so \\$P = \frac{2}{3}\frac{8}{8}\frac{6}{15}\frac{24}{24} + \frac{2}{3}\frac{6}{8}\frac{8}{15}\frac{24}{24} = \frac{4}{15} + \frac{4}{15} = \frac{8}{15}\\$

### Test Cases

*Using colour counts, sorted ascending...*

```
             [] => 1                   = 1/1
            [1] => 1                   = 1/1
            [2] => 1                   = 1/1
         [1, 1] => 0                   = 0/1
         [1, 2] => 0.6666666666666666  = 2/3
         [1, 3] => 0.8                 = 4/5
         [1, 4] => 0.8571428571428571  = 6/7
         [1, 5] => 0.8888888888888888  = 8/9
         [2, 2] => 0                   = 0/1
         [2, 3] => 0.5333333333333333  = 8/15
         [3, 3] => 0                   = 0/1
      [1, 1, 2] => 0.2736700336700337  = 2032/7425
      [1, 2, 2] => 0.12555631502999923 = 8266/65835
      [2, 2, 2] => 0.13119594210503302 = 75008/571725
      [2, 2, 3] => 0.1917063718196613  = 3352734487913/17488904808375
   [1, 1, 2, 2] => 0.10567693844206749 = 190686196363904/1804425820572375
   [1, 1, 2, 3] => 0.2161161470046424  = 4948035616451519666768/22895261113207012454925

```

# Answer
# Charcoal, ~~97~~ 93 bytes

```
≔⟦⊞ＯＡ¹⟧θＦθ«≔⊟ιη≔⟦⟧ζＦＬιＦΦκ⁻§ιλ§ικ⊞ζ⟦λκ⟧¿ζＦΦζ↨÷κ²±¹⊞θ⊞ＯＥΦι⁻÷μ²÷⌈κ²⎇⁼μ⌊κ§ι⁻｜⌈κ¹＆⌈κ¹λ∕ηＬζ⊞υη»Ｉ↨υ¹

```

Try it online! Link is to verbose version of code. Takes input as a flat list of lace end numbers and uses floating-point arithmetic to calculate the probability. Explanation: Brute force enumeration of lace tie patterns.

```
≔⟦⊞ＯＡ¹⟧θＦθ«

```

Start a breadth-first search with the input pattern with a probability of `1`.

```
≔⊟ιη

```

Get the probability of this pattern.

```
≔⟦⟧ζＦＬιＦΦκ⁻§ιλ§ικ⊞ζ⟦λκ⟧

```

Get the list of tieable lace end pair indices.

```
¿ζ

```

If the list is not empty, then:

```
ＦΦζ↨÷κ²±¹

```

Loop over the pairs of ends that don't form a loop.

```
⊞θ⊞ＯＥΦι⁻÷μ²÷⌈κ²⎇⁼μ⌊κ§ι⁻｜⌈κ¹＆⌈κ¹λ∕ηＬζ

```

Get the updated pattern after the current pair of ends are tied, include the new probability of this pattern, and save this to the list of patterns to search.

```
⊞υη

```

Otherwise, push the probability of this pattern to the running total.

```
»Ｉ↨υ¹

```

Output the final total.
> 5 votes

# Answer
# Python, ~~146~~ 142 bytes

```
f=lambda x,*_:sum(s:=[(n!=m)*f(y:=[(c,o-n or m-n)for c,o in x],*map(y.remove,[(a,m-n),(b,m-n)]))for a,n in x for b,m in x if a-b]or[1])/len(s)

```

Attempt This Online!

Takes input as a list of lace ends as lace color, lace identifier pairs with both represented as integers

```
f = lambda x, *_:
  sum(                              # sum(
    s := [                          #   s = [
      (n != m) *                    #     0 if same lace else
      f(                            #     recursive call with
        y := [                      #       y = [
          (c, o - n or m - n)       #         subtract n from identifer but set to m - n for n
          for c, o in x             #         for each lace end
        ],                          #       ]
        *map(                       #
          y.remove,                 #       remove from y
          [(a, m - n), (b, m - n)]  #       the chosen lace ends
        )                           #
      )                             #
      for a, n in x                 #     for each lace end a = color, n = identifier
      for b, m in x                 #     for each lace end b = color, m = identifier
      if a - b                      #     if different colors
    ]                               #   ]
    or                              #
    [1]                             #   s = [1] if all lace ends have same color
  ) / len(s)                        # ) / len(s)

```

---

# Python, ~~159~~ ~~157~~ 153 bytes

*-2 bytes thanks to @Jonathan Allan*

```
f=lambda x,*_:sum(s:=[a is not b and f(y:=x+[(a[q>1],b[~q%2])],*map(y.remove,[a,b]))for a in x for b in x for q in range(4)if a[q<2]-b[q%2]]or[1])/len(s)

```

Attempt This Online!

Takes inputs as a list of laces as pairs of equal numbers
> 5 votes

# Answer
# JavaScript (ES6), 138 bytes

*-11 thanks to Mukundan314*

Expects an array of laces, where each lace is a pair of integers representing its ends (e.g. `[0,0]`).

```
f=(a,n=t=0)=>a.map(p=>a.map(q=>[0,1,2,3].map(x=>t+=p[x>>1]-q[x&1]&&++n&&p!=q&&f([...a.filter(r=>r!=p&r!=q),[p[x/2^1],q[~x&1]]]))))|n?t/n:1

```

Try it online!

### Commented

```
f = (                     // f is a recursive function taking:
  a,                      //   a[] = input array
  n =                     //   n = counter
  t = 0                   //   t = sum
) =>                      //
a.map(p =>                // for each lace p in a[]:
  a.map(q =>              //   for each lace q in a[]:
    [0, 1, 2, 3]          //     there are 4 possible connections
    .map(x =>             //     for each connection x:
      t +=                //       update t:
        p[x >> 1] -       //         if the end of p does not
        q[x & 1] &&       //         match the end of q,
        ++n &&            //         then increment n
        p != q &&         //         if p and q are different laces,
        f([               //         then do a recursive call:
          ...a.filter(    //           pass a copy of a[]
            r =>          //           where:
            r != p &      //             the lace p and the lace q
            r != q        //             are removed
          ),              //           end of filter()
          [ p[x / 2 ^ 1], //           and a new lace made of the
            q[~x & 1] ]   //           opposite ends is added
        ])                //         end of recursive call
    )                     //     end of map()
  )                       //   end of map()
) |                       // end of map()
n ?                       // if n is not zero:
  t / n                   //   return the probability t / n
:                         // else:
  1                       //   return 1

```
> 5 votes

# Answer
# Python3, 497 bytes

```
lambda x:sum(f(x))
E=enumerate
S=sorted
u=lambda x:str(S(map(S,x)))
def f(a,p=1):
 if len(a)==1:yield p*(a[0][0]==a[0][1]);return
 d={}
 for i,j in E(a):
  if j[0]!=j[-1]:n=u(a[:i]+a[i+1:]);d[(n,0)]=d.get((n,0),0)+1
  for I,J in E(a):
   if i<I:
    F=[y for x,y in E(a)if x not in[i,I]]
    for j in[j,j[::-1]]:
     for J in[J,J[::-1]]:
      if j[-1]!=J[0]:n=u(F+[j[:-1]+J[1:]]);d[(n,1)]=d.get((n,1),0)+1
 if{}==d:yield p
 for x,y in d:
  if y:yield from f(eval(x),p*(d[(x,y)]/sum(d.values())))

```

Try it online!
> 2 votes

---
Tags: code-golf, combinatorics, probability-theory
---