title: XOR of independent Bernoulli variables

text:
# Question
Title: XOR of independent Bernoulli variables
In probability theory, a Bernoulli variable is a random variable which has a single parameter \\$p\\$, and is equal to 1 with probability \\$p\\$, and 0 with probability \\$1-p\\$.

In this challenge, there are a bunch of independent Bernoulli variables with parameters \\$p\_1, p\_2, ... , p\_n\\$, and their XOR is calculated. The XOR is 1 if an odd number of variables are 1, and 0 if an even number of variables are 1. Your task is to calculate the probability the XOR is 1.

# Test cases

```
# Format: [p1, p2, ..., pn] -> probability XOR is 1
[0.123] -> 0.123
[0.123, 0.5] -> 0.5
[0, 0, 1, 1, 0, 1] -> 1
[0, 0, 1, 1, 0, 1, 0.5] -> 0.5
[0.75, 0.75] -> 0.375
[0.75, 0.75, 0.75] -> 0.5625
[0.336, 0.467, 0.016, 0.469] -> 0.499350386816
[0.469, 0.067, 0.675, 0.707] -> 0.4961100146
[0.386, 0.224, 0.507, 0.099, 0.742] -> 0.499658027097344
[0.796, 0.019, 0, 1, 0.217] -> 0.338830368
[0.756, 0.924, 0.001, 0.046, 0.962, 0.001, 0.144] -> 0.6291619858201004

```

# Rules

* The input list will never be empty, \\$1\leq n\\$.
* You can use any reasonable I/O format. Some particular examples:
    + You can choose whether to take \\$p\_i\\$ or \\$1-p\_i\\$.
    + You can choose whether to output \\$p\\$ or \\$1-p\\$.
    + You can take the list of probabilities in any reasonable format.
    + You can take the length of the list as an additional input.
    + You can take the probabilities as fractions instead of floating-point numbers.
    + You can assume the probabilities are sorted.
    + You can take the probabilities as a multiset, or a map from probability to number of appearances.
* Your algorithm must in theory output exactly the correct answer, assuming its floating point calculations were perfect. In particular, you can't just simulate a finite number of trials.
* Standard loopholes are disallowed.

# Answer
# Haskell, 23 bytes

```
foldr1$ \x p->x+p-2*p*x

```

Try it online!

If you have two events with probabilities `x` and `p`, the probability of their xor is `p*(1-x)+x*(1-p)`, or `x+p-2*p*x`. `foldr1` folds this binary operator over the whole list.

A different approach that's longer in Haskell but may be golfier in other languages is to take the list product, but conjugated by the mapping `y=1-2*x`.

```
(\y->(1-y)/2).product.map(\x->1-2*x)

```

Try it online!

Or, since the challenge allowing inputs and outputs of one minus probabilities, we could conjugate by `y=2*x-1` instead:

```
(\y->(y+1)/2).product.map(\x->2*x-1)

```

Try it online!
> 16 votes

# Answer
# Python 2, 39 bytes

```
x=0
for p in input():x+=p-x*p*2
print x

```

Try it online!

**Also 39 bytes:**

```
lambda l:reduce(lambda x,p:x+p-x*p*2,l)

```

Try it online!

Folds (reduces) the binary function `(x,p)->x+p-2*p*x` like in my Haskell answer. The built-in `reduce` was removed in Python 3.

# Python, 36 bytes

```
f=lambda p=2,*t:p>1or(1-2*p)*f(*t)+p

```

Try it online!

Takes input splatted, and outputs 1 minus the probability. Works for Python 2 or 3.
> 9 votes

# Answer
# BQN, ~~8~~ 6 bytesSBCS

Based on xnor's Haskell answer, 2 bytes saved by att and BQN's extensions of logical functions to real numbers.

```
(∨-∧)´

```

Run online!

Spells the *XOR* out very literally now:  without .
> 7 votes

# Answer
# , 27 bytes

```
function(p).5-prod(1-2*p)/2

```

Try it online!

Based on @xnor's Haskell answer.
> 5 votes

# Answer
# Jelly, 5 bytes

```
ḤCPCH

```

A monadic Link that accepts the probabilities as a list of floats in \\$\[0,1\]\\$ and yields the XOR probability as a float.

**Try it online!**

### How?

```
ḤCPCH - Link: probabilities, P
Ḥ     - double {P} (vectorises)
 C    - complement (vectorises) e: 1-e
  P   - product
   C  - complement
    H - halve

```
> 4 votes

# Answer
# Python NumPy, 28 bytes

```
lambda i:.5-(1-2*i).prod()/2

```

Attempt This Online!

Takes a numpy array. Essentially a port of @xnor's approach (not the one they use but the one they mention in their Haskell answer).

## How?

Writing \\$q\_j := 1- p\_j\\$ compare the products (1) \\$\prod q\_j-p\_j\\$ and (2) \\$\prod q\_j+p\_j\\$. (1) can be rewritten (1') \\$\prod 1-2p\_j\\$, (2) is just a fancy way of writing \\$1\\$.

If we expand the two products (1,2) we get the same terms up to sign. In (2) all the terms are positive, in (1) it depends on whether there is an odd or even number of \\$p\_j\\$'s in the term. If we subtract (1) from (2) the terms with an even number of \\$p\_j\\$'s cancel and those with an odd number of \\$p\_j\\$ occur twice each. We can therefore compute the desired value by taking the product (1') subtracting it from 1 and dividing by 2

Writing this out in symbols is a bit heavy on notation:

\\$2\sum\_{I\subseteq \\{1,...,n\\}:|I|\text{ odd}}\prod\_{j\in I}p\_j\prod\_{j\not\in I}q\_j \\ =1-\sum\_{I\subseteq \\{1,...,n\\}}\prod\_{j\in I}-p\_j\prod\_{j\not\in I}q\_j \\\=1 - \prod q\_j-p\_j =1 - \prod 1-2p\_j\\$
> 3 votes

# Answer
# Charcoal, ~~9~~ 7 bytes

```
Ｉ⊘⊕Π⊖⊗Ａ

```

Try it online! Link is to verbose version of code. Explanation: Port of @xnor's second Haskell answer, but thanks to @xnor, using `q` for I/O instead of `p`.

```
      Ａ Input list
     ⊗  Vectorised doubled
    ⊖   Vectorised decremented
   Π    Take the product
  ⊕     Incremented
 ⊘      Halved
Ｉ       Cast to string
        Implicitly print

```

Previous 9-byte answer that uses `p` for I/O:

```
Ｉ⊘⁻¹Π⁻¹⊗Ａ

```

Try it online! Link is to verbose version of code. Explanation: Port of @xnor's second Haskell answer.

```
   ¹        Literal integer `1`
  ⁻         Subtract
      ¹     Literal integer `1`
     ⁻      Vectorised Subtract
        Ａ   Input list
       ⊗    Vectorised Doubled
    Π       Product
 ⊘          Halved
Ｉ           Cast to string
            Implicitly print

```

In succinct mode the input is actually implicit which would save me a byte on the above answers but it makes the verbose code look odd.

A port of @xnor's Python answer is 16 bytes:

```
≔⁰ηＦθ≧⁺×ι⁻¹⊗ηηＩη

```

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

```
≔⁰η

```

Start with a 0% chance that 0 variables have odd parity (in the computing sense).

```
Ｆθ≧⁺×ι⁻¹⊗ηη

```

For each variable, update the chances that the total parity is odd.

```
Ｉη

```

Output the final parity.

My original approach was 27 bytes:

```
⊞υ¹Ｆθ≔⁺×υ⁻¹ι×υιυＩΣΦυ﹪Σ⍘κ²¦²

```

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

```
⊞υ¹

```

Start with a 100% chance of 0 variables.

```
Ｆθ≔⁺×υ⁻¹ι×υιυ

```

For each variable, calculate the chances of that variable being `0` or `1`, given the chances of the previous variables.

```
ＩΣΦυ﹪Σ⍘κ²¦²

```

Sum the chances where the parity (in the computing sense) is odd.
> 3 votes

# Answer
# Arturo, 24 bytes

```
$=>[0loop&'p->+p-p*2*<=]

```

Try it!

Port of xnor's Python answer.

```
$=>[           ; a function where input is assigned to &
    0          ; push 0 to stack
    loop&'p->  ; loop over input, assign current element to p
    <=         ; duplicate top of stack
    2*         ; double
    p*         ; multiply by p
    p-         ; subtract from p
    +          ; add to sum (the 0 we pushed)
]              ; end function

```
> 2 votes

# Answer
# Thunno 2, 5 bytes

```
Ḍ⁻p⁺½

```

Attempt This Online!

Port of xnor's third Haskell answer.

#### Explanation

```
Ḍ⁻p⁺½  # Implicit input
Ḍ      # Double the input
 ⁻     # Decrement each
  p    # Take the product
   ⁺   # Increment it
    ½  # Halve
       # Implicit output

```
> 2 votes

# Answer
# Pyth, 8 bytes

```
.U_-*Zty

```

Try it online!

### Explanation

```
.U_-*ZtybbQ    # implicitly add the bbQ sauce
               # implicitly assign Q = eval(input())
.U        Q    # reduce Q on lambda b, Z with no starting value
       yb      #       2*b
      t        #       2*b-1
    *Z         #    Z*(2*b-1)
   -     b     #    Z*(2*b-1)-b
  _            #  -(Z*(2*b-1)-b) = b-Z*(2*b-1)
               #                 = b-Z*2*b+Z
               #                 = b+Z-2*b*Z

```
> 2 votes

# Answer
# C++ (gcc), ~~53~~ 47 bytes

```
[](auto&v,auto&x){x=0;for(auto p:v)x+=p-x*p*2;}

```

Try it online!

*Port of xnor's Python answer*
*Saved 6 bytes thanks to c--*
> 2 votes

# Answer
# 05AB1E, 5 bytes

```
·<P>;

```

Port of *@xnor*'s third Haskell answer, taking advantage of the \\$1-p\\$ input probabilities.

Try it online or verify all test cases.

**Explanation:**

```
·      # Double each value in the (implicit) input-list
 <     # Decrease each value by 1
  P    # Pop and push the product of the list
   >   # Increase it by 1
    ;  # Halve it
       # (after which the result is output implicitly as result)

```
> 2 votes

# Answer
# Nibbles, 9 bytes (18 nibbles)

```
/$:-+!\$_**`(!$_*~

```

Nibbles natively supports neither floating-point arithmetic nor fractions, so input is a list of 2-element lists of integers representing the numerator & denominator of each probability expressed as a fraction.
We then reduce the list with (in pseudocode):
`function( [xnum, xden], [pnum, pden] ) = [xnum*pden + pnum*xden - 2*xnum*pnum, xden*pden]`
and output the final probability as (non-reduced) numerator & denominator.

```
/$:-+!\$_**`(!$_*~      # full program
/$:-+!\$_**`(!$_*~$     # with implicit arg added;
/$                      # fold over input with this function:
    +                   #   first, get the sum of
     !                  #     zipping together
      \$                #       reverse of left element
        _               #       and right element
         *              #     by multiplication
   -                    #   now, subtract from this
          *      ~      #     2x
           `(           #     first element
                        #     (and remember 2nd element) of
             !          #     zipping together
              $         #       left element
               _        #       and right element
                *       #     by multiplication
 :                      #   and join to the rememebered 2nd element

```
> 1 votes

# Answer
# Scala, 30 bytes

Golfed version. Attempt this online!

```
_.reduceLeft((x,p)=>x+p-2*p*x)

```

Ungolfed version. Attempt this online!

```
import scala.io.StdIn.readLine
import scala.util.Try

object Main {
  def main(args: Array[String]): Unit = {
    Iterator.continually(readLine)
      .takeWhile(_ != null)
      .map(parseDoubles)
      .collect { case Some(list) => list }
      .map(compute)
      .foreach(println)
  }

  def parseDoubles(input: String): Option[List[Double]] = {
    val strippedInput = input.stripPrefix("[").stripSuffix("]")
    Try(strippedInput.split(',').map(_.trim.toDouble).toList).toOption
  }

  def compute(numbers: List[Double]): Double = {
    numbers.reduceLeft((x, p) => x + p - 2 * p * x)
  }
}

```
> 1 votes

# Answer
# Julia 1.0, 27 bytes

```
p>t...=(t.|>i->p+=i-2p*i;p)

```

Try it online!

Based on xnor's answer

29 bytes with recursion Try it online!

28 bytes with `reduce` Try it online!
> 1 votes

# Answer
# Mathematica (Wolfram Language) 18 bytes

This is an infix example of xnor's idea.

```
#1+#2-2#1#2&~Fold~

```

This gives the correct output on all the test cases. I would be interested to know if the arguments could be shortened using some kind of Sequence\[\].
> 1 votes

# Answer
# JavaScript (Node.js), 30 bytes

```
a=>a.map(p=>x+=p-x*p*2,x=0)&&x

```

Try it online!

Port
> 0 votes

# Answer
# ARM64 machine code, 32 bytes

This function takes as input a pointer to an array of 64-bit doubles in `x0`, and a pointer to the end of the array (one past last element) in `x1`. It returns the result in `d0`. This is consistent with standard calling conventions for a C function declared as `double xor_bernoulli(const double *array, const double *end);`, to be called like `xor_bernoulli(arr, arr+len)`.

```
2f00e400
fc408401
1f418002
1f418403
1e632840
eb01001f
54ffff63
d65f03c0

```

Assembly source:

```
    .global xor_bernoulli
    .text
    .balign 4
    // x0 = pointer to input
    // x1 = pointer to end

    // d0 will accumulate the probability
xor_bernoulli:
    movi d0, 0  // = 0.0
continue:

    // Compute p(1-q) + q(1-p) = (p-pq) + (q-pq)
    // let d0 = p
    ldr d1, [x0], #8       // d1 = q, x0 += 8
    fmsub d2, d0, d1, d0   // d2 = p-pq
    fmsub d3, d0, d1, d1   // d3 = q-pq
    fadd d0, d2, d3        // d0 = d2 + d3 = (p-pq) + (q-pq)

    cmp x0, x1
    b.lo continue

    ret

```

The fused multiply-subtract instruction is quite helpful here. It seems a little inefficient that we compute `pq` twice, thus doing two multiplies where only one is really needed, but I couldn't find a way to avoid it without more instructions.

I thought about trying to use SIMD instructions, but the best I could come up with was the following for the loop body:

```
continue:
    // on entry, v0 = [0, p]
    ld1 {v0.d}[1], [x0], #8          // v0 = [q, p]
    ext v1.16b, v0.16b, v0.16b, #8   // v1 = [p, q]
    fmls v0.2d, v0.2d, v1.2d         // v0 = [q-qp, p-pq]
    faddp d0, v0.2d                  // v0 = [0, q-qp + p-pq]

```

which is the same length. We can do both multiply-subtracts in parallel with vector `fmls`, but we need the extra `ext` shuffle instruction to make a copy with `p` and `q` swapped.
> 0 votes

---
Tags: code-golf, math, random, bitwise
---


title: Implement Subleq

text:
# Question
Title: Implement Subleq
Subleq is a Turing-complete esolang with only one instruction, SUBLEQ. This instruction takes in three parameters, `A`, `B`, and `C`, all of which are memory addresses. The instruction subtracts the value in memory address `A` from that in memory address `B`, storing it in address `B`. If the value at `B` is now less than or equal to zero, it jumps to memory address `C`; otherwise, it continues to the next instruction.

Your challenge is to implement this language. As input, the program should take in an array of integers representing the Subleq program, and starting at the first value (index `0`), execute the program. In general, if the program is at index `i`, you should execute `SUBLEQ(i,i+1,i+2)`. Your program should terminate when the instruction pointer is greater than the length of the tape; after execution, your program should output the final Subleq program with the memory modified.

If helpful, you may assume that you will only ever jump to locations which are a multiple of three. The behavior when the Subleq program runs into an error (e.g. jumps to a location outside memory) or get into an infinite loop are not defined.

## Example

Adapted from the Subleq esolang wiki page:

```
[3, 4, 3,
 6, 13, 9,
 6, 3, -3,
 7, 8, 3]

```

Here is a trace of the execution, where the first number is the instruction pointer and brackets are put around the currently executed line:

```
0 : [[3, 4, 3], 6, 13, 9,  6,  3, -3,  7, 8, 3 ]
3 : [ 3, 4, 3, [6,  7, 9], 6,  3, -3,  7, 8, 3 ]
9 : [ 3, 4, 3,  6,  7, 9,  6, -3, -3, [7, 8, 3]]
3 : [ 3, 4, 3, [6,  7, 9], 6, -3,  0,  7, 8, 3 ]
9 : [ 3, 4, 3,  6,  7, 9,  6, -9,  0, [7, 8, 3]]

```

Thus, your program should output

```
[3, 4, 3, 6, 7, 9, 6, -9, 9, 7, 8, 3]

```

Standard loopholes are forbidden. Since this is , the shortest program wins.

# Answer
# Python 3, 58 bytes

```
def f(s,i=0):a,b,*r=s[i:];s[b]-=s[a];f(s,[i+3,*r][s[b]<1])

```

A recursive function that updates a Subleq program, the list of integers `s`, in place terminating with a `ValueError`.

**Try it online!**
> 9 votes

# Answer
# x86(-64) machine code, 17 bytes

A function that **simulates a SUBLEQ machine with 8-bit cells**, returning to the caller with the array modified. Callable from C with the x86-64 SysV calling convention as `void subleq8(int8_t *end, int8_t *aligned_start);` (Like a `.begin()` / `.end()` range, the end pointer start+length.)

`start` must be aligned by 256 so its low 8 bits are `0`. This allows indexing the array by replacing the low byte with x86 partial-register stuff, instead of needing to zero-extend the guest byte into a separate register and use an indexed addressing mode. (A similar trick is useful on 8-bit systems like AVR where two 8-bit registers form a 16-bit pointer: if you don't cross a 256-byte boundary, you can skip `adc` into the high byte; if the array is aligned by 256 you can just replace the low byte.)

`start` must be in the low 32 bits of virtual address space, e.g. the x32 ABI, mmap(MAP\_32BIT), or simply a static array (e.g. in `.data`) in a non-PIE Linux executable. Or if you run the same machine code in 32-bit mode.

```
               ;;; array in ESI, aligned by 256 (so the low byte can be replaced to index into it)
               ;;; end-pointer (array+len) in EDI

               subleq8:
 89F0              mov  eax, esi               ; copy high bytes to EAX so merging a new low byte generates an address

               .nextinst:
 AC                lodsb                       ; fetch address A into AL, forming an x86 pointer in RAX
 8A 10             mov    dl, [rax]               ; deref A
 AC                lodsb                       ; fetch address B
 28 10             sub    [rax], dl            ; SUB and set FLAGS
 AC                lodsb                       ; fetch branch target address; RSI points at next instruction
 0F 4E F0          cmovle  esi, eax            ; update guest PC according to FLAGS

 39 FE             cmp    esi, edi             ; like cmp sil, dil  but range-shifted: both regs have the same high bytes
 72 F2             jb  .nextinst               ; len must be at most 127 to still consider *all* negative byte values as unsigned > 0x7f
 C3                ret

```

Instead of checking for the subtraction result being negative or zero, we actually check if `[b]` was less-or-equal than `[a]` before the subtraction, using FLAGS set by the `sub` instruction (like `cmp`). This is the same as checking the result against `0` if signed overflow didn't happen, otherwise it's the opposite. With Python arbitrary-precision integers, signed overflow is impossible. (There is no x86 FLAGS condition for negative-or-zero so it would take an extra 3 bytes, either for `cmp byte [rax], 0` or for `cmovs` \+ `cmove` instead of `cmovle`. Like most ISAs with signed-compare conditions, x86 does have a `le` less-or-equal condition that checks `SF != OF || ZF` in the same predicate.)

Apparently even Wikipedia defines a SUBLEQ OISC in terms of comparing against zero, rather than the usual computer-architecture meaning of a less-or-equal condition after a subtraction. :/ If signed wrap-around (overflow) doesn't happen, the two variants of the architecture are equivalent. Unless / until there's a test-case that requires checking the sign of the result instead of the LE condition generated by subtraction, I'm going to leave my answer this way. I'm pretty confident this is also Turing complete and probably not significantly different for implementing most basic arithmetic, if any of that comes near signed overflow.

**The max program length is 127 or 128 bytes** if you want *any* negative address to end the program. 126 is the highest multiple of 3, if your program doesn't do misaligned jumps and doesn't want to keep some data past the end of the last instruction. (It effectively treats the program counter as unsigned, looping `do {} while(PC < end)`, so a negative program counter is an unsigned number in the upper half of range, above any signed-positive length.) Otherwise, max program length = 255, exiting only on PC=255, although that's untested and rollover of the high bytes of RSI could happen, but maybe only with misaligned jumps, e.g. to PC=254 so fetching the full instruction would get to PC=257, with `lodsb` carrying into the higher bytes of RSI.

(With len limited to 128, misaligned jumps are no problem. e.g. a program might use its first instruction to jump to address `4` and then use the first 4 bytes purely as data, eventually falling off the end when PC = 128.)

Tested with the test-case in the question; it's correct for that but it doesn't AFAIK test for off-by-one errors (`<=` vs. `<` in the SUBLEQ operation), or for exiting via a taken branch to a negative or past-the-end address. I *think* my program is correct, e.g. `cmovle` treats "equal" the same as "less-than", and the test-case does exercise less-than causing the branch to be taken.

# x86(-64) machine code, 21 bytes

**Simulates a 32-bit SUBLEQ machine**. Writing a 32-bit register zero-extends to the full 64-bit register so even if we were willing to align the SUBLEQ program by 2^32 that wouldn't all the same partial-register trickery.

Even starting at absolute address `0` wouldn't work, because SUBLEQ addressing is in terms of cells, like a word-addressable machine. But x86 is a byte-addressable architecture, so SUBLEQ addresses have to be scaled by 4 to get x86-64 byte offsets since we're using 4-byte cells.

In x86-64 SysV, `void subleq32(int32_t *end, int32_t *start)`. I think the `start` pointer might need to be 4GiB aligned to properly handle all jumps to negative addresses, since we only compare the low 32 bits after doing `x86_address = base + target*4`. With a larger base, some negative targets could wrap. And due to the scaling by 4, the most negative value we detect is `-2^30`. We shift out the high bits of some larger numbers, although some larger-magnitude numbers will happen to have a bit that gets shifted to the sign-bit position, too.

So maybe it's only really able to correctly simulate a 30-bit SUBLEQ machine, or 29-bit or something. But still much more than 8-bit, which is the point.

```
                   ;; word-addressable SUBLEQ machine, where the components of an instruction are still 1 guest address apart
                   ;; despite them being farther apart in x86-64
               ;;; base address in ESI
               ;;; end address in EDI  (base+length in bytes, the one-past-end address.  An x86 address, not guest words)
               subleq32:
 89F1              mov  ecx, esi   ; save the base for later use.

               .nextinst:
 AD                lodsd                     ; fetch address A
 8B1481            mov    edx, [rcx+rax*4]   ; and deref; we don't need it after this
 AD                lodsd                     ; fetch address B
 291481            sub    [rcx+rax*4], edx   ; update [B] and set FLAGS
 AD                lodsd                     ; fetch branch target address; RSI points at next instruction for non-taken
 7F03              jnle  .not_taken
 8D3481            lea    esi, [rcx+rax*4]   ; scale the SUBLEQ target address to an x86 address
                   .not_taken:

 39FE              cmp    esi, edi
 72EE              jb  .nextinst       ; unsigned compare catches negative as well as past-the-end
 C3                ret

```

I also tested this with `dd` instead of `db` for the initial array, using GDB `print (int[12])prog32` after running, or `display` the same expression while single-stepping. This was my test caller:

```
section .data
prog32:
    dd 3, 4, 3,
    dd 6, 13, 9,
    dd 6, 3, -3,
    dd 7, 8, 3
prog32_end:

section .text
global _start
_start:
    mov edi, prog32_end
    mov esi, prog32
    call subleq32

    int3              ; software breakpoint

    xor edi, edi
    mov eax, 231
    syscall           ; x86-64 Linux exit_group(0)

```

## x86(-64) machine code for a byte-addressable SUBLEQ, 17 bytes

Untested, but it's the same logic as the 8-bit version, with the same instructions except 32-bit operand-size. (So writing full registers instead of merging into the low byte).

The SUBLEQ program's cells are 4 SUBLEQ addresses wide, matching the x86 addressing. One way to make the test program run the same is to scale all its starting values by 4, like `12, 16, 12 | 24, 52, 36 | ...`. If you do misaligned load/store or jumps, it will expose the fact that it's a little-endian machine. (SUBLEQ doesn't have byte loads, only word loads.)

This requires the array to start at absolute address `0`. Or in 32-bit mode, `DS:0`, so you could plausibly imagine some segmented code that sets the DS segment base for passing arrays. (Some "string" instructions use the ES segment, but `lodsd` uses `ds:esi`).

```
                   ;; byte-addressable SUBLEQ machine
               ;;; base address = 0
               ;;; end address = len in EDI
               subleq32b:
 31F6              xor  esi, esi               ; start address = 0, can't justify having the caller pass it since we depend on it being 0

               .nextinst:
 AD                lodsd                     ; fetch address A
 8B10              mov    edx, [rax]            ; and deref; we don't need it after this
 AD                lodsd                     ; fetch address B
 2910              sub    [rax], edx         ; update [B] and set FLAGS
 AD                lodsd                     ; fetch branch target address; RSI points at next instruction for non-taken
 0F4EF0            cmovle  esi, eax

 39FE              cmp    esi, edi
 72F2              jb  .nextinst       ; unsigned compare catches negative as well as past-the-end
 C3                ret

```

A 16-bit version of this would be highly plausible in 16-bit mode where segmentation is normal, then it wouldn't be too weird to take an array at `ds:0`. Same machine code except for the ModRM.rm field that encodes `[rax]`... except there is no `[ax]` addressing mode, only `[bx]`, `[di]`, or `[si]` for single-register 16-bit addressing modes that use the DS segment. So that might cost a couple 1-byte `xchg` instructions, perhaps with BX.

16-bit addressing modes don't allow a scale factor so they're not very convenient for a word-addressable SUBLEQ.
> 5 votes

# Answer
# JavaScript (ES6), 57 bytes

Modifies the input array.

```
f=(m,p=0)=>1/m[p]&&f(m,(m[m[p+1]]-=m[m[p]])>0?p+3:m[p+2])

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  m,              //   m[] = memory array
  p = 0           //   p = program counter
) =>              //
1 / m[p]          // abort if m[p] is undefined
&&                // otherwise:
  f(              //   do a recursive call:
    m,            //     pass m[]
    (             //
      m[m[p + 1]] //     subtract from m[m[p + 1]] ...
      -= m[m[p]]  //     ... the value stored at m[m[p]]
    ) > 0 ?       //     if the result is positive:
      p + 3       //       continue execution at p + 3
    :             //     else:
      m[p + 2]    //       jump at m[p + 2]
  )               //   end of recursive call

```
> 4 votes

# Answer
# Python3, 94 bytes:

```
def f(t,i=0):
 if i>=len(t):return t
 t[t[i+1]]-=t[t[i]];return f(t,[t[i+2],i+3][t[t[i+1]]>0])

```

Try it online!
> 2 votes

# Answer
# Charcoal, 45 bytes

```
Ｗ‹ⅈＬθ«≔§θ⊕ⅈι§≔θι⁻§θι§θ§θⅈ¿›§θι⁰Ｍ³→Ｊ§θ⁺²ⅈ⁰»⭆¹θ

```

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

```
Ｗ‹ⅈＬθ«

```

Repeat while the instruction pointer is within range.

```
≔§θ⊕ⅈι

```

Get the `B` parameter into a variable.

```
§≔θι⁻§θι§θ§θⅈ

```

Subtract the element at the `A` parameter from the element at the `B` parameter.

```
¿›§θι⁰

```

If the element at the `B` parameter is still positive, ...

```
Ｍ³→

```

... move to the next instruction, otherwise...

```
Ｊ§θ⁺²ⅈ⁰

```

.... jump to the `C` parameter.

```
»⭆¹θ

```

Output the final array.
> 2 votes

# Answer
# Z80 machine code, 22 bytes

```
44 4E 2C 0A 5F 4E 2C 0A 93 02 3D F2 1C 01 6E 2D 2C 7D BA D0 18 EB

```

Explanation of disassembled code:

```
; hl = Pointer to start of program. Must be aligned to 256 byte boundary.
; d = Length of the program in bytes.
subleq:
    ld b, h                     ; We want to use bc as a data pointer, so align
                                ; it to the same boundary as hl.
loop:
    ld c, (hl)                  ; Get a pointer to the first operand in bc and
    inc l                       ; advance the instruction pointer.

    ld a, (bc)                  ; Put the first operand in e.
    ld e, a

    ld c, (hl)                  ; Get the second operand pointer in the same
    inc l                       ; way as the first.

    ld a, (bc)                  ; Put the second operand in a and subtract e
    sub e                       ; from it, storing the result back where it
    ld (bc), a                  ; came from.

    dec a                       ; If the subtracted value was positive, skip
    jp p, no_jump               ; the jump.

    ld l, (hl)                  ; Load our new instruction pointer from the
    dec l                       ; third parameter. Decrement immediately since
                                ; we will increment next no matter what.
no_jump:
    inc l                       ; Advance the instruction pointer.

    ld a, l                     ; If we're past the end of the program, return.
    cp d
    ret nc

    jr loop                     ; Otherwise, continue our interpretation loop.

```

This is a plain Z80 subroutine called via `call` with registers as parameters. This subleq processor is 8-bit, both in data and addressing. Jump locations are interpreted as unsigned rather than signed, although comparisons are still signed. Do note that values are not exactly two's complement as `$80` is interpreted as positive rather than negative; however, the challenge does not specify this, and it should not affect the Turing-completeness of the implementation.

Example code to call the subroutine with the provided data:

```
    ld hl, prog_start
    ld d, prog_end - prog_start
    call subleq

    halt

    .align 256
prog_start:
    .db 3, 4, 3
    .db 6, 13, 9
    .db 6, 3, -3
    .db 7, 8, 3
prog_end:

```

You can paste these chunks of assembly into https://www.asm80.com/ to run them. Or, pull out your favorite Z80 system and run it there.
> 2 votes

# Answer
# \*, ~~84~~ 83 bytes

```
f=\(p,i=1)`if`(i>sum(p|1),p,f(p,`if`((p[j[2]]=diff(p[j<-p[i+0:2]+1]))<1,j[3],i+3)))

```

Attempt This Online!* or Try it online using `function` instead of the shorter `\` notation.

\*ATO uses a version of R (version 4.3.1) in which the `if` function errors when the condition has length \>1. Versions between 4.1.0 and \<4.2.0 just give a warning for this without halting with an error, and the header in the ATO link redefines the `if` function to mimic this behaviour.
It would cost +3 bytes to adjust the program to run in all versions of R ≥4.1.
> 2 votes

# Answer
# Python 3.11, ~~92 86 85~~ 62 bytes

This is *my* answer, so don't suggest copying from other answers.

```
def f(p,i=0):
 p[k:=p[i+1]]-=p[p[i]];f(p,(i+3,p[i+2])[p[k]<1])

```

Attempt This Online!

Takes in a program as a `list`, mutates the original list with an error (you need a variable and try/except to access the results).

Explanation:

```
def f(p,i=0):

```

Define the main function, `p` is the program to be ran and initialize the instruction pointer as `i`.

```
 p[k:=p[i+1]]-=p[p[i]];

```

Subtract A from B and store in B. Also assigns B as `k` to shave off bytes.

```
f(p,(i+3,p[i+2])[p[k]<1])

```

If B is less than 1, then recursively call with `i` as C, otherwise add 3.
> 1 votes

# Answer
# 05AB1E, ~~34~~ 33 bytes

```
[¾Ig@#Ðü3¾èRćU¬VèÆ©Yǝ®0›i3ë.µX}F¼

```

Try it online.

**Explanation:**

```
[         # Start an infinite loop:
 ¾        #  Push counter variable `¾` (which starts at 0)
  Ig      #  Push the input-length
    @     #  Pop both, and if `¾` is >= the input-length:
     #    #   Stop the infinite loop
          #   (after which the resulting list is output implicitly as result)
 Ð        #  Triplicate the current list
          #  (which will be the implicit input-list in the first iteration)
  ü3      #  Pop one copy and push its overlapping triplets
    ¾è    #  Pop and get the current Subleq-triplet [L[a],L[b],L[c]] at index `¾` (a)
  R       #  Reverse this triplet [L[a],L[b],L[c]] to [L[c],L[b],L[a]]
   ć      #  Extract its head; pop and push remainder-list and first item separately
    U     #  Pop and store L[c] in variable `X`
    ¬     #  Push the first item of the pair (without popping): L[b]
     V    #  Pop and store L[b] in variable `Y`
    è     #  Index [L[b],L[a]] in another copy of the list: [L[L[b]],L[L[a]]]
     Æ    #  Reduce this pair by subtracting: L[L[b]]-L[L[a]]
      ©   #  Store it in variable `®` (without popping)
       Y  #  Push L[b] from variable `Y`
        ǝ #  Insert L[L[b]]-L[L[a]] at index L[b] into the list
    i     #  If
 ®        #  L[L[b]]-L[L[a]] from variable `®`
  0›      #  is positive (>0):
     3    #   Push a 3
    ë     #  Else (it's <=0):
     .µ   #   Reset the counter variable `¾` to 0
       X  #   And push L[c] from variable `X`
    }     #  Close the if-else statement
     F    #  Loop that many times (either 3 or L[c]):
      ¼   #   Increase the counter variable by 1 every iteration

```
> 0 votes

# Answer
# Ruby, 55 bytes

```
->x,i=0{i=(x[x[i+1]]-=x[x[i]])>0?i+3:x[i+2]until !x[i]}

```

Attempt This Online!

Updates input array in-place.
> 0 votes

# Answer
# ARM64 machine code, 52 bytes

The SUBLEQ machine's memory is an array of signed 64-bit cells. This function takes a pointer to the array in `x0`, and the length of the array in cells in `x1`. It modifies the array in place. This matches standard ARM64 calling conventions for a C function `void subleq(uint64_t *mem, size_t len);`.

```
aa0003e2
a8c11043
f8408445
f8637806
f8647807
eb0600e7
f8247807
8b050c09
9a82d122
cb000043
eb010c7f
54fffec3
d65f03c0

```

Assembly source:

```
    .text
    .global subleq1
    .balign 4
    // 64 bit cells
    // here IP is a pointer
subleq1:
    // x0 = base of machine memory array
    // x1 = length of array
    // x2 = program counter
    mov x2, x0                  // pc=0
next_insn:
    ldp x3, x4, [x2], #16       // x3 = a, x4 = b, pc += 2
    ldr x5, [x2], #8            // x5 = c, pc += 1
    // now pc points to tentative next instruction
    ldr x6, [x0, x3, lsl #3]    // x6 = *a
    ldr x7, [x0, x4, lsl #3]    // x7 = *b
    subs x7, x7, x6             // x7 = *b - *a, set flags
    str x7, [x0, x4, lsl #3]    // store back to b
    add x9, x0, x5, lsl #3      // compute new pc corresponding to c
    csel x2, x9, x2, le         // select new pc if we had *b <= *a

    // check if pc still in range.
    // This could also be done with a cmp/ccmp pair, but same length.
    // Can save one instruction here if
    sub x3, x2, x0
    // x3 = offset of pc in bytes.
    cmp x3, x1, lsl #3
    // Check the unsigned result, so that negative pc corresponds to
    // very large value in x3, definitely higher than x1.
    b.lo next_insn

    ret

```

I couldn't find much clever golfing to do here. The load-store architecture hurts here as we need three instructions to do a read-modify-write of memory.

(Atomic `LDADD` is a possibility if we have ARMv8.2, despite being much more inefficient, but we'd need another instruction to negate the value from `a` as there is no `LDSUB`, and it wouldn't set the flags so that would cost one more. If the condition to jump were `*b - *a < 0` instead of `<=`, we could branch on the sign bit with `tbz`. `LDADD` also lacks the fancy addressing modes that we want to use.)

I took the same interpretation as Peter Cordes that signed overflow in the subtraction is undefined behavior, so that we can branch on `*b <= *a` instead of `*b - *a <= 0`.

It was also unclear what should happen if you jump to a negative address. This version will consider it successful termination. If you allow it to be UB, you can shave off one instruction (4 bytes) by changing the second argument (in `x1`) to be a pointer to the end of the array, instead of a length count, and then just change the loop condition to `cmp x2, x1; b.hs next_insn`.

I considered keeping an integer instead of a pointer as the program counter. It saves the `add` instruction to compute the new pc for `c`, but costs another one to add 3 for the no-jump case, because loads can't post-increment an index register.

I also had some thoughts about using 32-bit cells so that all three elements of the instruction could be loaded with one 128-bit `ldp`, but unpacking from the high half of a 64-bit register is too much extra work.
> 0 votes

# Answer
# Julia, 56 bytes

```
<(x,i=0)=(x[1+x[i+2]]-=x[1+x[i+1]])>0 ? x<i+3 : x<x[i+3]

```

Attempt This Online!

mutates the input and ends by erroring
> 0 votes

---
Tags: code-golf, interpreter
---


title: Compactify the input

text:
# Question
Title: Compactify the input
Given a word, your task is to compact it by saving its first character and removing any other vowel (aeiou).

# Input

Your input can be the word in STDIN, a function argument or any other input format that doesn't break the standard loopholes. You can assume the input only consists of lower characters.

# Output

Your output must be the word, compacted.

# Examples

```
i -> i
ate -> at
potato -> ptt
ksboejqfgcrauxpwivtzndlhmy -> ksbjqfgcrxpwvtzndlhmy

```

# Score

This is a code-golf, so shortest answer in bytes wins, good luck!

# Answer
# 05AB1E, 6 bytes

```
ćsžMм«

```

Try it online!

# Explanation

```
       Input (e.g.). potato
ć      Head extract. otato, p
 s     Swap        . p, otato
  žM   Vowels      . p, otato, aeiou
    м  Remove      . p, tt
     « Concatenate . ptt

Implicit output    .

```
> 7 votes

# Answer
# Retina, ~~15~~ ~~13~~ 8 bytes

```
0T1,`v`_

```

`T`ransliterates lowercase `v`owels into nothing (`_`) in the `0`th in 0-indexing match of the implicit regex that matches the entire string, after index 1 (`1,`).

Try it online!
> 5 votes

# Answer
# C (gcc), ~~57 56~~ 52 bytes

Time to roll out some magic numbers!

*Thanks @Arnauld for even better magic numbers!*

```
f(char*a,char*b){for(*b++=*a;*b=*++a;)b+=4373%*a&1;}

```

Try it online!
> 5 votes

# Answer
# , 15 bytes

```
{.,'aeiou'-.~}.

```

Try it online!

Straightforward:

* `{.` head...
* `,` catted with...
* `'aeiou'-.~` vowels, set minused from...
* `}.` tail
> 4 votes

# Answer
# sed, 14 bytes

```
s/\B[aeiou]//g

```

Try it online!

---

# Bash \+ Core utilities, 19 bytes

```
sed s/\\B[aeiou]//g

```

Try it online!
> 4 votes

# Answer
# Python 2, 43 bytes

Another 43-byte solution in Python.

```
lambda s:s[0]+s[1:].translate(None,'aeiou')

```

Try it online!
> 4 votes

# Answer
# Ruby, 31 bytes

```
->x{x[0]+x[1..].tr('aeiou','')}

```

Needs to be run on Ruby 2.6 or above, since it uses an endless range.

(TIO is on 2.5.5, so it doesn't work there.)
> 4 votes

# Answer
# Excel, 87 bytes

```
=LET(q,SEQUENCE(LEN(A1)),x,MID(A1,q,1),CONCAT(IF(ISERROR(FIND(x,"aeiou"))+(q=1),x,"")))

```

Hopefully this link works. Try it here
> 4 votes

# Answer
# Python 3, ~~44~~ 43 bytes

```
lambda a,*s:[a]+[c[c in"aeiou":]for c in s]

```

Try it online!

**Input**: Characters of the word. E.g `f("a", "t", "e")`
**Output**: A list of characters.
> 3 votes

# Answer
# Jelly, 6 bytes

```
Ḣ;ḟØẹ$

```

**Try it online!**

### How?

```
Ḣ;ḟØẹ$ - Link: list of characters, W
Ḣ      - head & yield
     $ - last two links as a monad - i.e. f(rest of W)
  ḟ    -   filter discard:
   Øẹ  -     lower-case vowels
 ;     - (head of W) concatenate (f(rest of W))

```
> 3 votes

# Answer
# naz, 102 bytes

```
2x1v2a6m8m1a2x2v4a2x3v4a2x4v6a2x5v6a2x6v1x1f1r3x1v2e3x2v1e3x3v1e3x4v1e3x5v1e3x6v1e1o1f0x1x2f0a0x1r1o1f

```

Works for any null-terminated input string.

Try it online!

**Explanation** (with `0x` instructions removed)

```
2x1v                                           # Set variable 1 equal to 0
2a6m8m1a2x2v                                   # Set variable 2 equal to 97 ("a")
4a2x3v                                         # Set variable 3 equal to 101 ("e")
4a2x4v                                         # Set variable 4 equal to 105 ("i")
6a2x5v                                         # Set variable 5 equal to 111 ("o")
6a2x6v                                         # Set variable 6 equal to 117 ("u")
1x1f                                           # Function 1
    1r                                         # Read a byte of input
      3x1v2e                                   # Goto function 2 if it equals variable 1
            3x2v1e3x3v1e3x4v1e3x5v1e3x6v1e     # Jump back to the start of the function
                                               # if it equals variable 2, 3, 4, 5, or 6
                                          1o1f # Otherwise, output it, then call the
                                               # function again
1x2f                                           # Function 2
    0a                                         # Add 0 to the register
1r1o                                           # Output the first byte of input
1f                                             # Call function 1

```
> 3 votes

# Answer
# Erlang (escript), 26 bytes

```
f([H|T])->[H]++T--"aeiou".

```

Try it online!

## Explanation

```
f([H|T])->       % Match the head & tail of the input string.
[H]              % Wrap the head in a list,
   ++T           % Append the tail
      --"aeiou". % with all vowels removed.

```
> 2 votes

# Answer
# APL (Dyalog), 14 bytes

```
⊃,'aieou'~⍨1∘↓

```

Try it online!
> 2 votes

# Answer
# Haskell, 34 bytes

```
f(a:s)=a:[x|x<-s,notElem x"aeiou"]

```

Try it online!
> 2 votes

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

```
s/(?<!^)[aeiou]//g

```

Try it online!
> 2 votes

# Answer
**APL (NARS2000 0.5.13.0), 20 unicode char (so 20 byte or 40 byte?)**

```
(↑,((~∘'aeiou')1∘↓))

```

Sample output:

```
      (↑,((~∘'aeiou')1∘↓)) 'i'
i
      (↑,((~∘'aeiou')1∘↓)) 'ate'
at
      (↑,((~∘'aeiou')1∘↓)) 'potato'
ptt
      (↑,((~∘'aeiou')1∘↓)) 'ksboejqfgcrauxpwivtzndlhmy'
ksbjqfgcrxpwvtzndlhmy
      (↑,((~∘'aeiou')1∘↓)) ''

```

Thanks to the tacit feature added lately.

Since APL code chars are unicode chars, I am not sure if one char should be counted as two byte or not.
> 2 votes

# Answer
# PHP, 41 bytes

```
<?=preg_replace("/\\B[aeiou]/","",$argn);

```

Try it online!

I wanted to find an original solution but it ends up like everyone's regex.. Deception is my middle name
> 2 votes

# Answer
# PowerShell, 33 30 bytes

-3 bytes thanks to @CommandMaster

```
$args-split"(.)[aeiou]"-join''

```

Try it online!
> 2 votes

# Answer
# Brachylog, 7 bytes

```
h|b;Ḅ∋ᵛ

```

Try it online!

Generator.

```
 |         The output is
h          the first element of the input,
 |         or
     ∋ᵛ    some shared element of
 |b        the input without its first element
   ;Ḅ      and the lowercase consonants.

```
> 2 votes

# Answer
# Factor, 31 bytes

```
[ 1 cut "aeiou"without append ]

```

Try it online!

## Explanation

It's a quotation (anonymous function) that takes one string as input and leaves one string as output. Assuming `"potato"` is on top of the data stack when this quotation is called...

* `1` Push one to the data stack. **Stack:** `"potato" 1`
* `cut` Cut a sequence into two pieces at a given index. **Stack:** `"p" "otato"`
* `"aeiou"` Push a string to the data stack. **Stack:** `"p" "otato" "aeiou"`
* `without` Remove elements from NOS (next on stack) that are in TOS (top of stack). **Stack:** `"p" "tt"`
* `append` Concatenate two strings. **Stack:** `"ptt"`
> 2 votes

# Answer
# Red, 33 bytes

```
func[s][trim/with next s"aeiou"s]

```

Try it online!
> 1 votes

# Answer
# Python 3, <sup>~~57~~</sup> 55 bytes

Saved 2 bytes thanks to ovs!!!

```
lambda s:s[0]+''.join(c for c in s[1:]if{c}-{*'aeiou'})

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6),  ~~27~~  26 bytes

*Saved 1 byte thanks to @Neil*

Returns a list of characters.

```
s=>s.match(/^.|[^aeiou]/g)

```

Try it online!
> 1 votes

# Answer
# K (oK), 20 bytes

```
{(*x),(1_x)^"aoeiu"}

```

Try it online!
> 1 votes

# Answer
# Python 3, 61 bytes

```
lambda s:s[0]+''.join(filter(lambda x:x not in'aeiou',s[1:]))

```

Try it online!
> 1 votes

# Answer
# Charcoal, 12 bytes

```
ΦＳ¬∧κ№aeiouι

```

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

```
 Ｓ              Input string
Φ ¬             Exclude characters where
     №aeiouι    Character is a vowel
   ∧κ           And index is not zero
                Implicitly print

```
> 1 votes

# Answer
# Keg `-ir`, ~~34~~ 16 bytes

Huge saving thanks to Lyxal.

```
,(:⅍`aeiou`-[,|_

```

Try it online!
> 1 votes

# Answer
# Pyth, 12 bytes

```
+hQ-tQ"aeiou

```

### Explanation

```
+hQ-tQ"aeiou
    tQ        : Everything except first element of evaluated input
   -  "aeiou  : Remove all occurrences of a, e, i, o and u from the string
+hQ           : Prepend first element of evaluated input

```

Try it online!
> 1 votes

# Answer
# Ruby `-p`, ~~22~~ 19 bytes

```
gsub /\B[aeiou]/,''

```

Try it online!

Thanks to Command Master for -3 bytes.
> 1 votes

# Answer
# JavaScript (V8), 42 bytes

```
s=>s[0]+s.substr(1).replace(/[aeiou]/g,'')

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
ö¶╫♂.

```

Run and debug it
> 1 votes

# Answer
# Japt v2.0a0, 7 bytes

```
Î+UÅr\v

```

Try it
> 1 votes

# Answer
# Arturo, 29 bytes

```
$[s][replace s{/\B[aeiou]}""]

```

Try it
> 1 votes

# Answer
# Vyxal `s`, 5 bytes

```
ḣkvF"

```

Try it Online!

Port of the 05Ab1e answer but one less byte because flags are cool
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 66 bytes

```
 INPUT LEN(1) . F REM . I
V I ANY('aeiou') =:S(V)
 OUTPUT =F I
END

```

Try it online!
> 0 votes

# Answer
# CJam, 15 bytes

```
l_0=\1>"aeiou"-

```

Try it online!

It's 15 bytes because there is no better way to push all those vowels.

## Explained

```
l_0=\1>"aeiou"-
l_                  e# Take the input and duplicate it: [input, input]
  0=                e# From the input, take the first character: [input, input[0]]
    \               e# Swap the top two items: [input[0], input]
     1>             e# Drop the first character: [input[0], input[1:]]
       "aeiou"      e# Push the string "aeiou": [input[0], input[1:], "aeiou"]
              -     e# Remove all occurances of the above string from the input[1:] and print.

```
> 0 votes

# Answer
# TI-Basic, 58 bytes

```
Input Str1
sub(Str1,1,1
For(I,2,length(Str1
If not(inString("AEIOU",sub(Str1,I,1
Ans+sub(Str1,I,1
End
Ans

```

Takes input as all capital letters (which is hopefully allowed).
> 0 votes

# Answer
# Uiua, 16 bytes

```
⍜↘(▽¬∊,"aeiou")1

```

Try it!

```
⍜↘(▽¬∊,"aeiou")1
⍜↘(           )1  # apply (...) to the input except the first letter
   ▽¬∊,"aeiou"    # remove vowels

```
> 0 votes

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


title: The too-short urinal problem

text:
# Question
Title: The too-short urinal problem
The well-known Urinal Protocol states that each person that takes a urinal will take the one furthest from any other taken urinal. But this fails to account for short urinals; in many cases, a person would prioritize taking a taller urinal in addition to distance.

In the real world, you might struggle to find a restroom with urinals of arbitrary height (besides a “short” and a “tall”) but fortunately for us this is the internet. To my knowledge, there are no guidelines for building internet bathrooms :P

For this challenge, you will be given a list of urinal heights and will have to determine the order in which they will be taken.

You might be given the following list:

```
3,2,4,3,1,4

```

The first person will choose the tallest urinal. In this case, there is a tie, so the leftmost urinal is taken, in this case urinal 3 (1-indexed).

```
_,_,1,_,_,_

```

The next person will take the tallest urinal that is further from any already taken urinal. Here, the tallest is urinal 6, and there is no tie.

```
_,_,1,_,_,2

```

The next person will take the next tallest, but if there is a tie, choose the urinal furthest from any already taken urinal.

```
3,_,1,_,_,2

```

We repeat the previous step until all slots are filled:

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

```

So the final answer here would be `3,5,1,4,6,2`.

But what about a situation like this:

```
3,2,1,2,1,1,3

```

The logic above applies until this state is reached:

```
1,4,_,3,_,_,2

```

Which of the three empty slots is preferable? They all have the same height, and are equidistant from the nearest taken urinal. Well, slot 3 is next to taken urinals on both sides, while slots 5 and 6 each have a side open, so they are preferable to slot 3. Now that the competition has narrowed to just two, the leftmost urinal is taken.

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

```

Importantly, the slots touching the edges (here 1 and 7) should be always be treated as though they have at least one side open. Consider this example:

```
1,2,1,1,3

```

The first two people come, and the third person sees this:

```
_,2,_,_,1

```

Here, the three remaining slots are actually all tied, because each has an open slot next to it, so the leftmost slot is taken:

```
_,2,_,_,1
3,2,_,_,1
3,2,4,_,1
3,2,4,5,1

```

The final result is `3,2,4,5,1`.

Test cases:

```
1 -> 1
1,1,1 -> 1,3,2
1,2 -> 2,1
1,2,1,1,3 -> 3,2,4,5,1
3,2,4,3,1,4 -> 3,5,1,4,6,2
1,3,3,2,4 -> 5,2,3,4,1
1,1,1,2,2 -> 3,4,5,1,2
1,1,1,1,1,1 -> 1,5,3,4,6,2
1,2,3,4,5 -> 5,4,3,2,1
2,1,1,3,1 -> 2,3,5,1,4
1,1,1,2,1,1,1,1,1,3,1,1,1 -> 3,6,10,2,7,11,4,8,12,1,9,13,5

```

## Clarifications

* The output numbers can start at 0 instead of 1.
* There will be no skipped urinal heights.

# Answer
# Jelly, 33 bytes

```
żJạṂ¥€¥_Je€ṖŻ+ḊƲɗɗNỤḟḣ1⁹;
“”ç@ƬṪỤ

```

Try it online!

A pair of links which is called with a single argument of urinal heights and returns the list of people at each urinal, as per the question spec.

*Thanks to @JonathanAllan for pointing out an error related to the use of .*

## Explanation

```
żJạṂ¥€¥_Je€ṖŻ+ḊƲɗɗNỤḟḣ1⁹;  # Helper link: takes the list of heights as the left argument and the current sequence of urinals used as the right; returns the updated sequence
ż                ɗ         # Zip the urinal lengths with the following:
      ¥                    # - Following as a dyad:
 J                         #   - Sequence 1..number of urinals
  ạṂ¥€                     #   - For each of those, minimum absolute distance from the existing people
       _        ɗ          # - Subtract the following run as a dyad on the original two arguments:
        Je€                #   - Generate a list of 1 in each used urinal position and 0 in those unused (sequence along original list, check whether each in current list)
               Ʋ           #   - Following as a monad
           Ṗ               #     - Remove last list member
            Ż              #     - Prepend zero
             +Ḋ            #     - Add to the untruthied list with the first member removed
                  N        # Negate
                   Ụ       # Indices in ascending value order (break ties from the left)
                    ḟ      # Filter out used indices
                     ḣ1    # First list member (can’t use Ḣ because this returns zero if list is empty)
                       ⁹;  # Append to existing list

“”ç@ƬṪỤ                   # Main link: take a list of urinal heights and return the list of people
“”ç@Ƭ                     # Starting with an empty list, call the helper link repeatedly with the current list on the right and the urinal heights on the left until there’s o change, gathering intermediate values
     Ṫ                    # Final version of list
      Ụ                   # Indices of list sorted by list values (takes sequence of urinals used and returns the people using the urinals as per spec)

```

Created with the help of Luminespire.
> 4 votes

# Answer
# Jelly, 24 bytes

-1 which led to one more thanks to Nick Kennedy!

```
Mạ¹ÐṂ;»Nḣʋ2ʋÞẹ0$ḢṬ¬aµƬṠS

```

A monadic Link that accepts the urinal heights as a list of positive integers and yields the urinal grading as a list of positive integers.

**Try it online!** Or see the test-suite.

### How?

Repeatedly chooses the next urinal, marking it occupied by changing its height to zero until all urinals are occupied, then recovers the grading from the results.

```
Mạ¹ÐṂ;»Nḣʋ2ʋÞẹ0$ḢṬ¬aµƬṠS - Main Link: Heights
                    µƬ   - start with X=Heights and collect while distinct, applying:
M                        -   maximal indices -> Highest
               $         -   last two links as a monad:
              0          -     zero
             ẹ           -     indices of {zero} -> Occupied
            Þ            -   sort {Highest} by:
           ʋ             -     last four links as a dyad - f(OneOfHighest, Occupied)
 ạ                       -       absolute differences
  ¹ÐṂ                    -       keep minimal values
         ʋ2              -       last four links as a dyad - f(Minimals, 2):
      »                  -         max with two (vectorises)
     ;                   -         {Minimals} concatenate {Minimals max 2}
       N                 -         negate
        ḣ                -         keep (up to) the first {2}
                Ḣ        -   head -> leftmost of farthest of highest -> Chosen
                 Ṭ       -   untruth (e.g. 5 -> [0,0,0,0,1])
                  ¬      -   logical NOT
                   a     -   logical AND {X} -> X with a zero at Chosen urinal
                      Ṡ  - signs
                       S - sum columns

```
> 3 votes

# Answer
# Charcoal, ~~63~~ 58 bytes

```
Ｗ∧⌈θＥθ∧⁼κ⌈θ⁻⁺χ⌊Ｅθ⎇›μ⁰↔⁻λνＬθΣＥθ∧‹μ¹‹↔⁻λν²§≔θ⌕ι⌈ι±ＬΦθ‹κ¹Ｉ⁻¹θ

```

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

```
Ｗ∧⌈θＥθ∧⁼κ⌈θ⁻⁺χ⌊Ｅθ⎇›μ⁰↔⁻λνＬθΣＥθ∧‹μ¹‹↔⁻λν²

```

Until all of the urinals are occupied, calculate the desirability of each urinal, which is zero for all urinals shorter than the tallest, or `10` plus the distance to the nearest occupied urinal minus the number of adjacent occupied urinals for the tallest urinals.

```
§≔θ⌕ι⌈ι±ＬΦθ‹κ¹

```

Mark the leftmost urinal of those of equal maximum desirability as occupied using the negation of the number of previously occupied urinals. The first of these will be zero, which will cause the loop to exit once all of the urinals are marked as occupied.

```
Ｉ⁻¹θ

```

Output the final list of orders.
> 2 votes

# Answer
# , 113 bytes

```
\(x,s=seq(x),y=!x){for(i in s)y[order((.5/(sapply(s,\(w)min((w-s[!!y])^2))+!c(y[-1],0)*c(0,y)[s])-x)*!y)[1]]=i;y}

```

Attempt This Online!

A function taking a vector of urinal heights and returning a vector of people. The warnings generated occur on the first pass through when the people vector has no one in but do not affect the result.
> 2 votes

# Answer
# Python3, 219 bytes

```
E=enumerate
def f(u):
 c,C=1,[0]*len(u)
 while 0==all(C):I=max([i for i,a in E(C)if 0==a],key=lambda i:(u[i],min([abs(I-i)for I,A in E(C)if A]or[0]),(i-1<0 or 0==C[i-1])+(i+1>=len(u)or 0==C[i+1])));C[I]=c;c+=1
 return C

```

Try it online!
> 2 votes

---
Tags: code-golf
---


# Question
Title: Split a list at the second occurrence of the first element
Why should you golf in Haskell? Find out here. In that answer, Zgarb defines a task:

> Let's define a function `f` that splits a list at the second occurrence of the first element, e.g. `[0,2,2,3,0,1,0,1] -> ([0,2,2,3],[0,1,0,1])`:

Alright then, lets!

You are to take a non-empty list consisting of digits, and output a **pair** of lists, clearly distinguished, such that the output is the input split before the second occurrence of the first element.

For example, you may output two strings of digits with a non-digit separator. The separator you choose between the elements of each pair and the pairs themselves must be distinct (e.g. space and newline), consistent and not contain digits.

The output must only contain **2** elements however. You may not output empty lists in the output. If you choose to use newlines as a separator between pairs, you may not have a leading newline. You may have trailing newlines no matter what, and you may have trailing whitespace, so long as its sensible.

You may assume:

* The input will be provided in any convenient method, and you may output in any convenient method
* The input will either be a list of digits, or a string
* The input will only contain the integers `0` though to `9`
* The first element of the input will always occur at least twice
* The input will always have 3 or more elements in it

Additionally, this is , so the shortest code in bytes wins

## Test cases

```
[1, 1, 9] -> [[1], [1, 9]]
[4, 9, 4] -> [[4, 9], [4]]
[5, 7, 5, 5] -> [[5, 7], [5, 5]]
[8, 8, 0, 7] -> [[8], [8, 0, 7]]
[7, 1, 5, 7, 4, 2] -> [[7, 1, 5], [7, 4, 2]]
[0, 6, 9, 1, 1, 0, 2] -> [[0, 6, 9, 1, 1], [0, 2]]
[2, 9, 3, 2, 4, 2, 5, 9] -> [[2, 9, 3], [2, 4, 2, 5, 9]]
[0, 2, 2, 3, 0, 1, 0, 1] -> [[0, 2, 2, 3], [0, 1, 0, 1]]
[2, 7, 4, 6, 2, 6, 6, 4, 8, 2] -> [[2, 7, 4, 6], [2, 6, 6, 4, 8, 2]]
[8, 2, 2, 7, 5, 4, 7, 0, 8, 0, 7] -> [[8, 2, 2, 7, 5, 4, 7, 0], [8, 0, 7]]
[8, 7, 8, 9, 4, 2, 9, 4, 5, 7, 5, 1, 9] -> [[8, 7], [8, 9, 4, 2, 9, 4, 5, 7, 5, 1, 9]]
[3, 8, 1, 1, 7, 3, 6, 9, 7, 1, 4, 3, 4] -> [[3, 8, 1, 1, 7], [3, 6, 9, 7, 1, 4, 3, 4]]
[4, 7, 0, 5, 6, 5, 0, 1, 7, 8, 7, 8, 4, 1] -> [[4, 7, 0, 5, 6, 5, 0, 1, 7, 8, 7, 8], [4, 1]]
[2, 1, 8, 0, 3, 2, 2, 5, 7, 9, 4, 3, 5, 1, 9, 6, 9] -> [[2, 1, 8, 0, 3], [2, 2, 5, 7, 9, 4, 3, 5, 1, 9, 6, 9]]
[1, 1, 4, 1, 2, 5, 5, 3, 3, 4, 3, 2, 0, 8, 6, 0, 3] -> [[1], [1, 4, 1, 2, 5, 5, 3, 3, 4, 3, 2, 0, 8, 6, 0, 3]]
[4, 3, 5, 2, 2, 0, 6, 4, 8, 6, 6, 6, 7, 3, 4, 8, 7, 6] -> [[4, 3, 5, 2, 2, 0, 6], [4, 8, 6, 6, 6, 7, 3, 4, 8, 7, 6]]

```

# Answer
# AWK, 17 14 bytes

```
sub(FS$1,RS$1)

```

Try it online!

*Thanks to Pedro Maimere for the hint to lop off 3 bytes*

The interactions of the rules in the contest allow for pretty trivial AWK solution... Assuming the input can be a blank delimited string of numbers, this will work. If it has to include the brackets and commas (which I wasn't sure about from the linked article about convenient input), then it would be this instead.

```
sub(", "(a=substr($1,2)),"]\n["a)

```

And here's one in `><>` which might be shrinkable still... It's the first time I've managed to get something to work in that language, so I wouldn't be surprised to learn there some trick I don't know yet.

# \>\<\>, 41 bytes

```
i:o&0v
?(0:i<o$v?<=1:+{=&:&:;
 0+1o+19< ^

```

Try it online!

I can add a more detail description if anyone is interested, but here's an overview of how it works.

The input it expects is a string of digits. Since the challenge specified that the list was made up of single digit numbers, I chose not to include a delimiter. If that's a requirement, some additional stuff would have to be added...

The first line reads in the first number, uses it to set the register (for comparison as the rest of the list is read in), then pushes a counter that tracks the number of times the first number has been seen. Then it passed control down to the next line.

```
i:o&0v

```

That line reads one digit at a time, starting with the second digit, and prints it. There's a conditional code to add a `\n` when the counter hits `1` (meaning it found the second occurrence of the first digit). The code is interpreted right to left to save characters.

```
?(0:i<o$v?<=1:+{=&:&:;

```

The last line is effectively like a "function" call to print a linefeed and tweak the counter so that it will never be called again.

```
0+1o+19< ^

```
> 11 votes

# Answer
# Haskell, 26 bytes

```
f(x:y)=([x],0)*>span(/=x)y

```

Try it online!

Shortens Zgarb's OG solution

```
f(x:y)|(a,b)<-span(/=x)y=(x:a,b)

```

by prepending `x` to the first element of `(a,b)` in a pointfree way, that is without explicitly binding `(a,b)`.

It would be nice it we could do `(x:)<$>(a,b)`, but that gives `(a,x:b)` -- the Functor instance of tuples lets us act on the second element but not the first.

However, Applicative lets us combine tuples as:

```
(p, f) <*> (a, b) = (p++a, f b)
([x], id) <*> (a, b) = (x:a, b)

```

It suffices to use `*>` which ignores `f` and leaves `b` unchanged.

```
((x:), 0) *> (a, b) = (x:a, b)

```

The `0` could be anything -- it doesn't matter. It would also work to use `>>` in place of `*>`.

**26 bytes**

```
f(x:y)=([x],y)>>=span(/=x)

```

Try it online!

A alternative, this time using the Monad instance and `(>>=) :: Monoid a => (a, a0) -> (a0 -> (a, b)) -> (a, b)`

**27 bytes**

```
f(x:y)=([x],[])<>span(/=x)y

```

Try it online!

Using `<>` to do concatenate elementwise `(a, b) <> (c, d) = (a++c, b++d)`. This is available in Prelude without an import starting in version 8.4.1.
> 11 votes

# Answer
# Vim, 3 bytes/keystrokes

```
*O<esc>

```

Jump to next occurrence of word and make a new line.

---

# V (vim), 2 bytes

```
*O

```

Try it online!

Since V has implicit escape after `O` (?), we can use just 2 bytes.

---

Old (general) 8-byter:

```
Y/<C-r>"<BS><CR>O<esc>

```

---

Input is each list item on a single line. Output is two lists separated by a blank line.

Uses vim notation for the keystrokes (`<C-r>` is `Ctrl`-`R`, *etc.*; see `:help key-notation`).

Explanation:

* `Y` yank the first line
* `/<C-r>"<BS><CR>` search for the next occurrence by inserting the yanked text into a search `/`. Yanking into the search register with `"/Y` doesn't work (`:help quote/`). The backspace deletes the line-ending, which is yanked. (Alternately, use `y$/<C-r>"<CR>`.)
* `O<esc>` new blank line above.

This generalizes to any type of list as long as each element is a single line.

---

I don't think we can use POSIX vi for this, since I don't think it has `<C-r>` to insert registers. It doesn't have the search register `"/`, but that doesn't end up mattering.
> 11 votes

# Answer
# Vyxal, ~~18~~ 7 bytes

```
Ṙṫ:‟€vp

```

Try it Online!
> 8 votes

# Answer
# Jelly, 7 bytes

```
œṡḢ©®;Ɱ

```

Try it online!

```
œṡḢ©®;Ɱ  Main Link
œṡ       Split at the first occurence of
  Ḣ      The first element (pops the element)
   ©     (also copies that element to the register)
      Ɱ  For each block
    ®;   Prepend the register

```

As pointed out by Nick Kennedy in the comments (full credit to them), `Ḣ;Ɱœṡ@¥` also works and is slightly more functionally pure (though  still modifies the list itself, so it's not entirely pure):

```
Ḣ;Ɱœṡ@¥  Main Link
Ḣ        Cut off and return the first element
      ¥  Last two as a dyad (for chaining; this makes the right argument the modified list for both inner dyads rather than applying consecutively)
 ;Ɱ      Prepend the first element to each of
   œṡ@   The modified list, split at the first occurrence of the first element

```
> 7 votes

# Answer
# Factor, ~~37~~ 35 bytes

```
[ dup first 1 pick index-from cut ]

```

Try it online!

## Explanation:

* `dup` Duplicate the input.

**Stack:** (e.g.) `{ 0 2 2 3 0 1 0 1 } { 0 2 2 3 0 1 0 1 }`
* `first` Get first element.

**Stack:** `{ 0 2 2 3 0 1 0 1 } 0`
* `1` Push `1`.

**Stack:** `{ 0 2 2 3 0 1 0 1 } 0 1`
* `pick` Put a copy of the object third from the top on top of the stack.

**Stack:** `{ 0 2 2 3 0 1 0 1 } 0 1 { 0 2 2 3 0 1 0 1 }`
* `index-from` Find the index of `0` starting from index `1` in the sequence on top of the stack.

**Stack:** `{ 0 2 2 3 0 1 0 1 } 4`
* `cut` Split a sequence in two at an index.

**Stack:** `{ 0 2 2 3 } { 0 1 0 1 }`
> 7 votes

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

```
{(2#*=x)_x}

```

Try it online!

* `(...)_x` cut the input (`x`) at...
    + `2#*=x` the indices of the first two occurrences of the first value in the input
> 7 votes

# Answer
# Python 3.8, 41 bytes

```
lambda l:[l[:(i:=l.index(l[0],1))],l[i:]]

```

Try it online!
> 6 votes

# Answer
# Retina 0.8.2, ~~18~~ 17 bytes

```
^((.).*?)\2
$1¶$2

```

Try it online! Link is to test suite that double-spaces the output for convenience. Takes input as a string of digits. Explanation: Simply finds the earliest next match of the first character and inserts a newline before it. Edit: Saved 1 byte thanks to @Jakque.
> 6 votes

# Answer
# JavaScript (ES6), 31 bytes

Thanks Razetime for -1 byte.

```
a=>a.match(/^(.).*?(?=\1)|.+/g)

```

Try it online!
> 6 votes

# Answer
# , 17 16 bytes

```
(]{.,<@;@}.)<;.1

```

Try it online!

In a sentence:

*Cut on first element and then meld together the tail elements.*

Consider `f 0 2 2 3 0 1 0 1`

* `<;.1` Cut using the first element as the fret:

```
┌───────┬───┬───┐
│0 2 2 3│0 1│0 1│
└───────┴───┴───┘

```
* `{.,<@;@}.` First element of that result `{.` catted with tail of that result `}.`, razed `;` and then reboxed `<@`.

```
┌───────┬───────┐
│0 2 2 3│0 1 0 1│
└───────┴───────┘

```
> 5 votes

# Answer
# **BQN**, 12 11 bytesSBCS

```
⊢⊔˜·∨`·»⊑=«

```

Try it here.

Explanation:

```
⊢⊔˜·∨`·»⊑=«   # tacit function which can take input as either a list or a string
          «   # the input list shifted left
         =    # equality comparison with
        ⊑     # the first element of the input
      ·»      # shift the result right
   ·∨`        # 'or' scan
⊢⊔˜           # group the input according to those values

```
> 5 votes

# Answer
# , ~~38~~ ~~37~~ 36 bytes

*Edit: -1 byte thanks to pajonk, as well as outputting the right-way-around now, and then -1 byte thanks to digEmAll*

```
function(l)by(l,cumsum(l==l[1])>1,c)

```

Try it online!
> 5 votes

# Answer
# Scala, ~~35~~ 30 bytes

Saved 5 bytes thanks to @cubic lettuce!

```
x=>x splitAt x.indexOf(x(0),1)

```

Try it in Scastie!

Hopefully, I'm not FGITW'ing this.
> 4 votes

# Answer
# Zsh, 35 bytes

```
shift>$1
ls
for x
(rm $x&&od;<<<$x)

```

Try it online!

Explanation:

* `>$1`: create a file named the first input item
* `shift`: shift the input array, removing the first item
* `ls`: list the directory. Since we created `$1`, this prints the first item
* `for x`: for each item `$x` in the input array: `(`
    + `rm $x`: try to remove the item. If the item `$x` is the same as the first input, and the item has not already been removed, this will succeed
    + `&&`: if that succeeds:
        - `od`: print `0000000` as a separator
    + `<<<$x`: print the item

With some loose interpretation of what is allowed as a separator, we could have:

## Zsh, 33 bytes

```
shift>$1
ls
for x
rm -v $x||<<<$x

```

Try it online!

* `rm -v` is `v`erbose; if the removal is successful, a message `removing 'x'` is printed which is arguably a separator, as well as printing the item
* `||`: if that fails:
    + `<<<$x`: print the item. We only need to do this if removal fails, because `rm -v` prints the item already
> 4 votes

# Answer
# Red, 49 46 bytes

```
func[x][reduce[take/part x find next x x/1 x]]

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 26 bytes

```
g[b_,a___,b_,c___]=b.a|b.c

```

Try it online!

-10 bytes thanks to @att
> 3 votes

# Answer
# Haskell, 56 bytes

```
f(h:t)=(h#t)[h]
(h#(x:y))a|x==h=(a,x:y)|0<1=(h#y)$a++[x]

```

Try it online!

Because why not?

## flawr's suggestion, 33 bytes

```
f(x:y)|(a,b)<-break(==x)y=(x:a,b)

```

Try it online!

This is based on Zgarb's solution (`f(x:y)|(a,b)<-span(/=x)y=(x:a,b)`).
> 3 votes

# Answer
# JavaScript (ES6), 34 bytes

```
a=>[a,a.splice(a.indexOf(a[0],1))]

```

Try it online!
> 3 votes

# Answer
# PowerShell Core, ~~60~~ 57 bytes

```
$a,$b=$args
$r=(,$a),$y
$b|%{$r[$r[1]-or$_-eq$a]+=,$_}
$r

```

Try it online!

It takes the input as an array of ints, returns two arrays

### Another approach for 59 bytes

```
param($a)$a[0..(($i=$a|% i*f $a[0] 1)-1)],$a[$i..$a.Length]

```

Try it online!

Takes the input as a string, returns two arrays
> 3 votes

# Answer
# Red, 67 bytes

```
func[b][collect[keep/only take/part b find next b b/1 keep/only b]]

```

Try it online!
> 3 votes

# Answer
# Python 2, 45 bytes

```
i=input()
a=i.index(i[0],1)
print i[:a],i[a:]

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~8~~ 7 bytes

```
ćk>Ig‚£

```

Try it online or verify all test cases.

**7 bytes alternative provided by *@ovs*:**

```
ćk>°RÅ¡

```

Try it online or verify all test cases.

**Explanation:**

```
ć       # Extract head of the (implicit) input-list; pop and push remainder-list and
        # first item separated to the stack
 k      # Get the first 0-based index of this item in the remainder-list
  >     # Increase it by 1 to make it a 1-based index
   Ig   # Get the length of the input-list
     ‚  # Pair them together
      £ # And split the (implicit) input-list into parts of that size
        # (after which the result is output implicitly as result)

ćk>     # Same as above
   °    # Pop and push 10 to the power this 1-based index
    R   # Reverse it, so we have a 1 with some leading 0s
     Å¡ # Split the (implicit) input-list at the truthy indices (or singular index in
        # this case: the 1)
        # (after which the result is output implicitly as result)

```
> 3 votes

# Answer
# Vyxal , 5 bytes

```
hẆḢḣf

```

Try it Online!

Explanation:

```
h      # Get the first element of the list
 Ẇ     # Split list on head, without removing it from the list
  Ḣḣ   # Get the first element from the resulting list
    f  # Flatten the rest of the resulting list
       # 'ṡ' flag - print both lists, separated by a space

```
> 3 votes

# Answer
# Japt, 8 bytes

Feels like there should be a shorter way for this, but can't seem to find it right now.

Selecting the right-hand element ensures we don't select the first letter itself, the check on the incremented variable ensures we only split once.

```
óÏ¦UÎªT°
ó        // Split the input string between char pairs where it's not true that
 Ï       // the right-hand element
  ¦      // is different than
   UÎ    // the first char of the input
     ª   // or
      T° // T, initially equals zero, plus plus.

```

Try it here.
> 3 votes

# Answer
# JavaScript (V8), 54 bytes

```
x=>[x[s="slice"](0,i=x[s](1).indexOf(x[0])+1),x[s](i)]

```

Try it online!
> 2 votes

# Answer
# MATLAB/Octave, 63 bytes

```
function y=f(x)
l=find(x==x(1));y={x(1:l(2)-1),x(l(2):end)};end

```

Try it online!
Outputs cell aray with 2 cells, which hold appropriate vectors. I've chosen such output because rules say 2 lists must be distinguished, not necessarily be separate variables. And outputting 2 variables turned out to give a little longer code.

Ungolfed/explained:

```
function y = f(x)
l = find( x==x(1) );   % indices of elements equal to first element
l2 = l(2);             % index of second occurence
y = { x(1:(l2-1)),...  % vector containing elements before 2nd occurence
      x(l2:end) };     % vector containing elements from 2nd occurence
end

```

---

Interestingly, it's also possible to create anonymous function that does the same, but it's 2 bytes longer:

```
@(x){x(1:find(x(2:end)==x(1),1)),x(find(x(2:end)==x(1),1)+1:end)}

```

Try it online!
It is possible to shorten it more as flawr noticed, resulting in **42 bytes** but it's an **Octave-only** solution, not working for MATLAB:

```
@(x){x(1:(l=find(x==x(1))(2))-1),x(l:end)}

```

Try it online!
> 2 votes

# Answer
# Stax, 10 bytes

```
τÄ∩T╕(û▒(Ç

```

Run and debug it

annoyingly long, but i guess it works.

### Stax, 12 bytes(regex)

```
êt┴≈∟·M╤\+6)

```

Run and debug it

### Stax, 22 bytes(tsh's regex)

```
"^(.).*?(?=\1)|.+$"|Fm

```

Run and debug it
> 2 votes

# Answer
# Husk, 12 bytes

```
Fȯ:;:←¹↕≠←¹t

```

Try it online!

no split at index builtin, but  (span) helps a bit.

it's similar to xnor(and Zgarb)'s answer, but argument destructuring and functors don't exits, so it just uses a fold.
> 2 votes

# Answer
# Vyxal, 8 bytes

```
ḣ$£¥€ƛ¥p

```

Try it Online!

This is possible in 8 bytes Imao
> 2 votes

# Answer
# \>\<\>, 21 bytes

```
<0o{oa.0*3+)3l=}:{::i

```

Try it online!

Takes input as a list of characters (though you are free to put whatever you want in-between digits). Managed to reuse my check that we're not splitting on the first input with the jump quite nicely.

### Explanation

```
<                      Go left from the start
                  ::i   Get the input and duplicate it twice
              =}:{      Compare it with the first character of the input
           )3l          Check if this is not the first char
        *3+             Add these checks together and multiply by 3
                        This will be 3 if the digit is not the same, or if it is the first digit, otherwise 6
      .0                Jump to that point on the first line
   {oa                  If it is the split point, print a newline and clear the first digit
  o                     Print the current digit
 0                      Push a zero to increase the stack height for the first digit check

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 13 bytes (SBCS)

Anonymous tacit prefix function

```
⊢⊂⍨1,⊃<\⍤=1↓⊢

```

Try it online!

the argument

`1↓` drop first element

… apply the following tacit infix function to that, with the first element of the argument as left argument:

`⍤=` Boolean mask indicating where they are equal

`<\` cumulative right-associative less-than scan (effectively zeroes any one after the first one)

`1,` prepend a one

`⊢⊂⍨` use that to partition the argument, starting a new segment on every 1
> 2 votes

# Answer
# Python 3.8, 40 chars

If outputting a list of two strings is allowed...

```
lambda s:[s[:(i:=s.find(s[0],1))],s[i:]]

```
> 2 votes

# Answer
# C (gcc), ~~58~~ 57 bytes

-1 byte thanks to ceilingcat

Takes input as a string. Outputs to STDOUT.

```
l;f(char*s){l=index(s+1,*s)-s;printf("%.*s %s",l,s,s+l);}

```

Try it online!
> 2 votes

# Answer
# TI-BASIC, 69 bytes (on-calc) / 104 bytes (as text)

```
Ans→A
2→I
While ⌊A(I)≠⌊A(1
I+1→I
End
Disp seq(⌊A(J),J,1,I-1
seq(⌊A(J),J,I,dim(⌊A

```

## Explanation

* `Ans→A`: The program stores a list in `⌊A` from `Ans` by calling it like this: `{list}:prgmL`
* `2→I`: Initialize `I` with 2
* `While ⌊A(I)≠⌊A(1`: While the current element is not equal to the first
    + `I+1→I`: Increment `I`
* `End`
* `Disp seq(⌊A(J),J,1,I-1`: Display the first chunk of the list
* `seq(⌊A(J),J,I,dim(⌊A`: Implicitly display the second chunk of the list

## Earlier overcomplicated solution, 78 bytes (on-calc) / 130 bytes (as text)

```
Ans→A
Ans=Ans(1:Ansseq(I,I,1,dim(Ans→B
SortD(⌊B
⌊B(sum(Ans>0)-1
Disp seq(⌊A(I),I,1,Ans-1
seq(⌊A(I),I,Ans,dim(⌊A

```
> 2 votes

# Answer
# Brain-Flak, 112 bytes

```
((({})<>)<>){{}({}<(({})<>)<>>)({<({}[()]<({}[()])>)>()}{}<>)<>({}<<>({}<>)>)}{}((()()()()()){})<>{}{({}<>)<>}<>

```

Try it online!
> 2 votes

# Answer
# C (gcc), 66 bytes

```
k;f(d,l)int*d;{k=printf(" %d"+(!l||d[l]-f(d,l)),k=d[--l])-1?-1:k;}

```

Try it online!
> 1 votes

# Answer
# Clojure, 44 bytes

```
#(split-at(inc(.indexOf(rest %)(first %)))%)

```

Try it online!
> 1 votes

# Answer
# \>\<\>, 18 bytes

```
i:vi
=?\o:i:@
oa<^

```

Try it online!

Saves a copy of the first character `x` at the bottom of the stack, compares the read character to that, and then prints a line feed and enters an infinite `io` loop when it finds the second instance of `x`.

This was a nice instance of being able to use the 2D-ness of `><>` by reusing the singular `o` for both a horizontal and a vertical loop.
> 1 votes

# Answer
# PowerShell, ~~47~~ ~~42~~ ~~39~~ 38 bytes

```
$args-split"(?<=.)(?=$("$args"[0]))",2

```

Try it online!
> 1 votes

# Answer
# Python 3, 41 bytes

```
def f(a):a.insert(a[1:].index(a[0])+1,-1)

```

Try it online!

Another Python approach using the allowed flexible output format. Not any shorter than the existing solution.
> 1 votes

# Answer
# Jelly, 6 bytes

```
CiḢ$Ṭk

```

Try it online!

Took me embarrassingly long to realize that `œṖ` splits before, but `k` splits after...

```
C         Subtract each element from 1, creating a new list object.
  Ḣ       Remove its first element and then
 i $      find its first index in that list.
    Ṭ     Create an array containing a 1 at that index,
     k    and split the original array after that 1.

```

With no mutation at all:

# Jelly, 6 bytes

```
Ḋiḷ/Ṭk

```

Try it online!
> 1 votes

# Answer
# Lolwho.Cares, 169 bytes

```
*2*+210021**+102201*1*1>*2+011021`02**+2101,12000002001v                 v<0210002,<
                       ^120<210<021<<<<<<<<`---020-----,120120*101+201021>*2+00210>^
0210002

```

Note: The last line is not counted as code, it is the input.
> 1 votes

# Answer
# Pip `-p`, 11 bytes

```
a^@(a@*@a1)

```

Takes a string of digits and outputs a list of two digit-strings. Try it online!

### Explanation

```
             a is first command-line arg (implicit)
    a@*      In a, find all indices of
       @a    the first character of a
   (     1)  Get the second index in the list (0-indexed)
a^@          Split a at that index

```
> 1 votes

# Answer
# PHP, 89 bytes

```
function($x){$y=array_keys($x,$x[0])[1];return[array_slice($x,0,$y),array_slice($x,$y)];}

```

Try it online!

## Explanation:

* `array_keys` returns all index positions of an element. Accessing `$x[1]`, we get the second occurrence.
* `array_slice` Gets you a subpart of the array. Param =\> (array, start, length\[optional\])
> 1 votes

# Answer
# Kotlin, 151 bytes

Takes a `List<Int>` as input and returns a `Pair<List<Int>, List<Int>>`

```
{l:List<Int>->val u=mutableListOf<Int>()
var d=l.size
l.forEachIndexed{i,n->if(!u.contains(n))u.add(n)else d=i}
l.slice(0..d-1)to l.slice(d..l.size-1)}

```
> 1 votes

# Answer
# Zsh, ~~37~~ 26 bytes

Using Zsh array parsing. The separator is an underscore, `_`

```
A=$@
<<<${(SI:2:)A/$1/_$1}

```

Try it Online! ~~37 bytes~~
> 1 votes

# Answer
# Arturo, 35 bytes

```
$[a][split.at:+1index drop a 1a\0a]

```

Try it

```
$[a][               ; a function taking an arg a
  split.at: ... a   ; split a at a particular index
  +1                ; add one to
  index ... a\0     ; the index of the first elt of a in ...
  drop a 1          ; a without its first elt
]                   ; end function

```
> 1 votes

# Answer
# TypeScript (4.9.4) - ~~161~~ 79 Bytes

Note this is only using the type system, so computation is done at compile time

* 82 Bytes thanks to **@ASCII-only**!

```
type S<N,H=[]>=N extends[,...infer R]?N[0]extends H[0]?[H,N]:S<R,[...H,N[0]]>:0

```

example usage:

```
type TestOne = Split<[1, 1, 9]>

```

ungolfed version (original):

```
type Split<Nums extends any[], Comp extends any = null, Head extends any[] = []> =
  // get first element of nums and rest
  Nums extends [infer First, ...infer Rest] ?
  // check if compare is not set
  Comp extends null ?
  // set comp to first and nums to rest call recursively
  Split<Rest, First> :
  // check if first and comp are equal
  First extends Comp ?
  // return [Head, Nums] if true
  [[Comp, ...Head], Nums] :
  // move First into Head and call recursively
  Split<Rest, Comp, [...Head, First]> :
  // return null if nothing
  null

```

Try it online!
> 1 votes

# Answer
# Raku, 21 bytes

```
{S[(.).*?<()>$0]="
"}

```

Try it online!

A regex-based approach. Input is a string of space-separated digits, output is the same string but with the space between the digits where the list should be broken replaced with a newline.
> 1 votes

# Answer
# Desmos, 93 bytes

```
a=length(l)
b=\min([2...a](9sign(l[2...a]-l[1])^2+1))
f(l)=join(l[1...b-1],join(-1,l[b...a]))

```

Test on \\$f(l)\\$, where \\$l\\$ is the inputted list.

Outputs the two lists combined into one, separated by a \\$-1\\$ element in between. This is allowed.

For example, `[1,1,9] -> [[1], [1,9]] -> [1,-1,1,9]`

Try It On Desmos!

Try It On Desmos! - Prettified
> 0 votes

# Answer
# Uiua, 10 bytes

```
⊃↘↙⊡1⊚=⊢..

```

Try it!

```
⊃↘↙⊡1⊚=⊢..
        ..  # duplicate twice
       ⊢    # first
      =     # mask where input is equal to its first element
     ⊚      # which indices are true?
   ⊡1       # get the second one
⊃↘↙         # split input at this index

```
> 0 votes

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