# Question
Title: Maximum population of a \$n \times n\$ still life in Conway's Game of Life
This is OEIS sequence A055397.

In Conway's Game of life, a **still life** is a pattern that does not change over time. We can see from the rules of Conway's Game of life that, a pattern is a still life if and only if:

* every living cell has exactly two or three living neighbors,
* none of the dead cells have three living neighbors.

Given a positive integer \\$n\\$, what is the maximum number of living cells of a still life in a \\$n \times n\\$ bounding box?

The following table shows the results for small \\$n\\$s: (Screenshot from the book *Conway's Game of Life - Mathematics and Construction* by Nathaniel Johnston and Dave Greene)

In 2012, G. Chu and P. J. Stuckey gave a complete solution for all \\$n\\$.

When \\$n \> 60\\$, the results are:

$$\begin{cases} \lfloor n^2/2 + 17n/27 - 2 \rfloor, & \text{ if } n \equiv 0, 1, 3, 8, 9, 11, 16, 17, 19, 25, 27, \\ & \quad \quad \ \ \ \\, 31, 33, 39, 41, 47, \text{or } 49 \ (\text{mod } 54) , \text{ and} \\ \lfloor n^2/2 + 17n/27 - 1 \rfloor, & \text{ otherwise}. \end{cases}$$

When \\$n \le 60\\$, the results are not so regular. They are given in the testcases.

## Task

Given a positive integer \\$n\\$, output the maximum number of living cells of a still life in a \\$n \times n\\$ bounding box.

As with standard challenges, you may choose to either:

* Take an input \\$n\\$ and output the \\$n\\$th term in the sequence.
* Take an input \\$n\\$ and output the first \\$n\\$ terms.
* Output the sequence indefinitely, e.g. using a generator.

This is , so the shortest code in bytes wins.

## Testcases

```
1 0
2 4
3 6
4 8
5 16
6 18
7 28
8 36
9 43
10 54
11 64
12 76
13 90
14 104
15 119
16 136
17 152
18 171
19 190
20 210
21 232
22 253
23 276
24 301
25 326
26 352
27 379
28 407
29 437
30 467
31 497
32 531
33 563
34 598
35 633
36 668
37 706
38 744
39 782
40 824
41 864
42 907
43 949
44 993
45 1039
46 1085
47 1132
48 1181
49 1229
50 1280
51 1331
52 1382
53 1436
54 1490
55 1545
56 1602
57 1658
58 1717
59 1776
60 1835
61 1897
62 1959
63 2022
64 2087
65 2151
66 2218
67 2285
68 2353
69 2422
70 2492
71 2563
72 2636
73 2708
74 2783
75 2858
76 2934
77 3011
78 3090
79 3168
80 3249

```

# Answer
> 6 votes
# Python 2, 99 bytes

```
lambda n:n*(27*n+34)/54+(~0x282828a0b0b0b>>n%54&1)-(0x9f4f41e064109edb1e1397137967e232263/5**n+2)%5

```

Try it online!

The formula in the challenge description works pretty well for \\$n\<60\\$ and is always within 2 of the actual value, so we first calculate the formula:

```
  n*(27*n+34)/54+~(0x282828a0b0b0b>>n%54&1)
= n*(27*n+34)/54+(~0x282828a0b0b0b>>n%54&1)-2

```

And add the offset:

```
  -(0x9f4f41e064109edb1e1397137967e232263/5**n+2)%5+2

```

The `-2` and `+2` cancel out

# Answer
> 4 votes
# MATL, 32 bytes

```
UTFZ^!"@GeTTYat3Y6QZ+5:7m=?@svX>

```

Brute force. Times out for input exceeding `3`. Part of the code reused from this answer.

Takes *n* as input. Try it online!

### How it works

```
U             % Input (implicit): n
TF            % Push [1, 0]
Z^            % Cartesian power: all Cartesian tuples of length n containing
              % 1 or 0. Gives a matrix with n^2 columns, where each row is a
              % Cartesian tuple
!"            % For each row
  @           %   Push current row
  Ge          %   Reshape with n rows (and n columns)
  TTYa        %   Add a frame of zeros
  t           %   Duplicate
  3Y6QZ+5:7m  %   Perform one iteration of the Game of Life (see linked answer)
  =?          %   If all entries (before and after the iteration) are equal
    @s        %     Push sum of current row (that is, number of active cells)
    vX>       %     Concatenate with previous result, if any, and take maximum
              %   End (implicit)
              % End (implicit)
              % Display (implicit)

```

# Answer
> 2 votes
# JavaScript (Node.js), 122 bytes

```
n=>n*n/2+17*n/27+1-("1201304124344333343332333333322423223224232332232322323323223"[n]||2+(706447126760203/2**(n%54)&1))|0

```

Try it online!

Uncompressed table

# JavaScript (Node.js), 109 bytes

```
n=>n*(34+27*n)/54+!(706447126760203/2**(n%54)&1)-[0xbffab022c9fe1aebcdf9b3aabadf0e5376en.toString(5)[n]||2]|0

```

Try it online!

Indirect port of gsitcia's solution

# Answer
> 2 votes
# Charcoal, 57 bytes

```
ＮθＩ⁻÷×⁺×²⁷θ³⁴θ⁵⁴⊖§⁺”)⊞E?ü⍘ï″ê&8,⁴&0Ｓ6.¬↶”…”{∨>~iRz÷↙Ｊa”θθ

```

Try it online! Link is to verbose version of code. Explanation: Based on the formula in the challenge description, but looks up the value to subtract in one of two lookup tables, depending on whether the input is greater than `60` or not.

```
Ｎθ                              First input as an integer
        ²⁷                      Literal integer 27
       ×                        Multiplied by
          θ                     Input integer
      ⁺                         Plus
           ³⁴                   Literal integer 34
     ×                          Multiplied by
             θ                  Input integer
    ÷                           Integer divided by
              ⁵⁴                Literal integer 54
   ⁻                            Subtract
                   ...          Compressed lookup table for 0..60
                  ⁺             Concatenated with
                       ...      Compressed lookup table for 61..114
                      …         Cyclically extended to length
                          θ     Input integer
                 §              Indexed by
                           θ    Input integer
                ⊖               Decremented
  Ｉ                             Cast to string
                                Implicitly print

```

# Answer
> 1 votes
# Python 3, 285 bytes

```
lambda n:max(map(len,[q for s in r(n**2+1)for q in combinations([(x,y)for x in r(n)for y in r(n)],s)if{*q}==g(q,n)]))
g=lambda c,n:{(x,y)for x in r(-1,n+1)for y in r(-1,n+1)if sum((q,r)in c for q in[x-1,x,x+1]for r in[y-1,y,y+1])in[[3],[3,4]][(x,y)in c]}
r=range
from itertools import*

```

Try it online!

Times out pretty fast because it just brute-forces. Pretty sure it's \\$O\left(2^{n^2}\right)\\$ but it could be worse.

# Answer
> 1 votes
# 05AB1E, 87 bytes

```
•1ÏUΓ’∍GTšƒΘQ74₅βvćsZý[Σi—т°/βΩùŠ·ćeeðZGïQ©.†•60в.¥In;17I*27÷+<•6WÁ.‹Ñ•7в.¥I54%å-ª.ÞI<è

```

Boring approach: hard-codes the values \\$\leq60\\$, and calculates the values \\$\gt60\\$ given the formula in the challenge description.

I might try to a brute-force approach later, but 05AB1E overall isn't too great at matrix challenges.

Try it online or verify all test cases.

**Explanation:**

```
•1ÏUΓ’∍GTšƒΘQ74₅βvćsZý[Σi—т°/βΩùŠ·ćeeðZGïQ©.†•
             # Push compressed integer 54764668022476930839561631116267184217708747839781677738253594755809981424425189706066485884825983031999
 60в         # Convert it to base-60 as list: [4,2,2,8,2,10,8,7,11,10,12,14,14,15,17,16,19,19,20,22,21,23,25,25,26,27,28,30,30,30,34,32,35,35,35,38,38,38,42,40,43,42,44,46,46,47,49,48,51,51,51,54,54,55,57,56,59,59,59]
    .¥       # Undelta with leading 0: [0,4,6,8,16,18,28,36,43,54,64,76,90,104,119,136,152,171,190,210,232,253,276,301,326,352,379,407,437,467,497,531,563,598,633,668,706,744,782,824,864,907,949,993,1039,1085,1132,1181,1229,1280,1331,1382,1436,1490,1545,1602,1658,1717,1776,1835]
I            # Push the input-integer
 n           # Square it
  ;          # Halve it
   17I*      # Push the input*17
       27÷   # Integer-divided by 27
          +  # Add those two together
           < # Decrease it by 1
•6WÁ.‹Ñ•     # Push compressed integer 6607718158603
 7в          # Convert it to base-7 as list: [1,2,5,1,2,5,1,2,6,2,4,2,6,2,6,2]
   .¥        # Undelta with leading 0: [0,1,3,8,9,11,16,17,19,25,27,31,33,39,41,47,49]
     I       # Push the input-integer
      54%    # Modulo-54
         å   # Check if it's in this list
          -  # Subtract that check
ª            # Append it to the earlier list of 60 values
 .Þ          # Infinitely cycle this trailing item
   I<è       # Pop the list and get its 0-based (input-1)'th value
             # (after which it is output implicitly as result)

```

See this 05AB1E (sections *How to compress large integers?* and *How to compress integer lists?*) to understand how the compression works.

# Answer
> 1 votes
# Befunge-98 (PyFunge), 236 bytes

```
 <v.ke0"$+6@LZhw.AUk3Lf >\z?b+Qw Jr Jv'U		8	h"a'a"Q=s"c-'cf'd!'d"\U"0F='(4"FPSP"
kv>'}*+.:!
$
>:::M2FD\:'FM'FD\I'6%4gFNAAI.1FA

```

Code is almost entirely unprintables, many of which get omitted by Stack Exchange's markdown renderer. See the TIO link for the full code.

Brief explanation:

1. The first line is set-up, which first enables the `FPSP` fingerprint, then pushes 61 as a floating-point number, and a zero as a sentinel value for later. The rest of the first line is a base-124 encoding of the hardcoded numbers for still lifes of value less than 60. The `.ke` at the beginning of the first line (since code is read in reverse) mean "execute the `.` instruction 0xe (14) times", printing the values less than 124.
2. The second line just prints the values that are greater than 124 but still hardcoded, until it reaches the sentinel.
3. The third line is a `$`, which discards the `0` sentinel from earlier. At this point the 61 and then some garbage is left on the stack.
4. The fourth line does the formula part; each `/` separated segment is one of the terms on the equation.

```
:::                                 Makes 3 copies of the index being output (leaving 4 on the stack)
   M                                Multiplies the first two together, leaving n^2 and 2 copies of N
    2FD                             Divides by two, leaving N^2/2 and 2 copies of N
       \:                           Swap the top two values and duplicate, leaving 2 copies of N, then n^2 \ 2, then 1 more copy of N
         ' FM' FD                   Do the multiplying by 17 and dividing by 27 for the second term (there's an unprintable character after each ')
                  \I                Swap the top two values, then convert the number to an integer. Stack at this point is N then 17n/27 then n^2/2 then N again
                    '6%4g           Mod N by 54, then look it up in the lookup table in the fourth line of code (which is all unprintables)
                         FN         Convert it from a positive integer to a negative floating-point number
                            AAI.    Add all of the terms on the stack together, convert it to an integer, and output
                                1FA Increment the index on the stack by one for the next iteration.

```
5. The fifth line of code is a lookup table for whether to subtract one or two. It is never actually executed, merely read using Befunge's ability to look at its own source code.

Try it online!

---
Tags: code-golf, sequence, game-of-life
---


title: Resolve a Super Auto Pets Round

text:
# Question
Title: Resolve a Super Auto Pets Round
In Super Auto Pets, players build teams of animals that face off in battles to ~~the death~~ unconsciousness. Each animal has an Attack and Health value, and combat occurs in iterations of the following process:

1. The front animals of each team deal damage to each other equal to their Attack at the same time.
2. Both animals lose Health points equal to the damage taken. Health points are never restored in battle.
3. Animals with 0 Health or less faint and are removed from the battle.

As an example consider two teams A and B, which will be represented by a list of tuples (Attack, Health).

A: \[(2, 3), (2, 2), (3, 1)\] B: \[(1, 3), (3, 4), (1, 2)\]

To illustrate the battle, the teams will be displayed so that the front animals are facing each other. I will also label each animal for convenience. A battle between these teams would go as follows:

```
         Pig   Beaver  FishA        Duck   FishB  Otter
Step 0: (3, 1) (2, 2) (2, 3) -> <- (1, 3) (3, 4) (1, 2)
A and B line up opposite each other, with their first animals ready to attack . The arrows show the direction each team is facing.
Step 1: (3, 1) (2, 2) (2, 2)   |   (1, 1) (3, 4) (1, 2)
FishA and Duck attack each other, with FishA dealing 2 damage, and Duck dealing 1. Both are still conscious, so they will attack again next step.
Step 2: (3, 1) (2, 2) (2, 1)   |   (3, 4) (1, 2)
This time FishA leaves Duck with -1 HP, so Duck faints, but FishA survives its attack. Next for B is FishB, but FishA is still alive.
Step 3:        (3, 1) (2, 2)   |   (3, 2) (1, 2)
FishB knocks out FishA and survives FishA's attack with 2 HP. Now Beaver gets to attack
Step 4:               (3, 1)   |   (1, 2)
Beaver and FishB both drop to 0 HP and faint, leaving only Pig and Otter
Step 5:                        |
Otter and Pig knock each other out, leaving no more pets.

```

Since neither A or B was resilient enough to survive the battle, the result is a draw. If A had any pets left when B's Otter fainted, A would have won (and similar for B in the opposite case).

### The Challenge

Your challenge is to write a program or function which takes two teams of pets and outputs the result of their battle. The teams may be empty, and do not have to have the same number of pets.

Your input format may consist of any structure(s) describing the order of each team and the Health and Attack of each animal in that order. Above I have used a list of tuples, each list representing a team in order, and each tuple representing one animal. However, you do not have to conform to this format as long as your input contains the necessary data.

Your solution should output one of three distinct values (which you should specify!) corresponding to a win by the first team, a win by the second team, or a draw. To fulfill this, you also must specify which parts of your input correspond to which team

Standard I/O rules apply, and this is Code Golf, so shortest answer wins.

### Examples

The examples take input in the first method described, and output either "A wins!", "B wins!", or "Draw!". I have created a reference implementation in Python 3 on TIO.

```
A: [(1, 3), (3, 1), (3, 2), (2, 2), (6, 5), (5, 7)]
B: [(3, 1), (1, 1), (1, 2), (1, 2), (4, 3)]
Result: A wins!

A: [(2, 2)]
B: [(2, 2)]
Result: Draw!

A: []
B: [(1, 1)]
Result: B wins!

A: [(1, 3), (3, 1)]
B: [(3, 1), (1, 1), (1, 2), (1, 2), (4, 3)]
Result: B wins!

```

# Answer
> 3 votes
# Charcoal, 56 bytes

```
ＵＭθ⮌ιＷ⌊θ«≔Ｅθ⊟κιＵＭιＥκ⎇ν⁻μ§§ι¬λ⁰μＦ²¿›⌊§ικ⁰⊞§θκ§ικ»Ｉ↨Ｅθ¬ι±¹

```

Try it online! Link is to verbose version of code. Takes input as a pair of lists of tuples and outputs `1` if `A` wins, `-1` if `B` wins and `0` for a draw. Explanation:

```
ＵＭθ⮌ι

```

Reverse each list so that the front animals are now at the end of the lists.

```
Ｗ⌊θ«

```

Repeat while both teams have animals.

```
≔Ｅθ⊟κι

```

Pop the front animals from both of the lists.

```
ＵＭιＥκ⎇ν⁻μ§§ι¬λ⁰μ

```

Perform an attack.

```
Ｆ²¿›⌊§ικ⁰⊞§θκ§ικ

```

Push those animals that still have positive health back to their team.

```
»Ｉ↨Ｅθ¬ι±¹

```

Output the final result.

# Answer
> 3 votes
# Jelly, 28 bytes

```
z0_ṚŻ€$Ṗ€Ɗ€1¦»0ZȦƇ€µƬẈ€ẠÞḢIṠ

```

A monadic Link that accepts a list of the teams as lists of animals each of which is a list of positive integers, `[attack, health]`, and yields `[-1]` if the first team wins, `[0]` if there is a draw, or `[1]` if the second team wins.

**Try it online!**

### How?

```
z0_ṚŻ€$Ṗ€Ɗ€1¦»0ZȦƇ€µƬẈ€ẠÞḢIṠ - Link: teams
                   µƬ        - collect up input while distinct, repeatedly applying:
z0                           -   transpose the teams with filler 0 (pair up animals)
         Ɗ€1¦                -   apply to the first pair of animals:
      $                      -     last two links as a monad:
   Ṛ                         -       reverse
    Ż€                       -       prefix each with a zero
  _                          -     animals subtract that (vectorises)
       Ṗ€                    -     remove the last (third) value from each
             »0              -   max with zero (vectorises)
               Z             -   transpose back to teams
                ȦƇ€          -   for each team keep those without zeros
                     Ẉ€      - length of each for each collected input
                       ẠÞ    - sort by: all?
                         Ḣ   - head
                          I  - forward differences
                           Ṡ - sign (vectorises)

```

# Answer
> 2 votes
# Perl 5, 112 bytes

```
sub{($A,$B)=@_;while(@$A&&@$B){map$_[$_][0][1]-=$_[1-$_][0][0],0,1;map$$_[0][1]<1&&shift@$_,@_}@$A?A:@$B?B:Draw}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 32 bytes

```
[D€gW_#\Â‚ε`нUćXR0Dǝ-W1@išë\]`.S

```

Assumes the attacks of animals are always positive.
Input as a pair of lists of pairs, where the first inner pairs are the attacking animals. Outputs `-1` if team A wins; `0` if it's a draw; and `1` if team B wins.

Try it online or verify all test cases.

**Explanation:**

```
[            # Loop indefinitely:
 D           #  Duplicate the current pair of lists
             #  (which is the implicit input in the first iteration)
  €g         #  Pop the copy, and get the length of each inner list
    W        #  Push the minimum length (without popping)
     _       #  If this smallest length is 0 (so a team is without animals):
      #      #   Stop the infinite loop
    \        #  If not, discard the list of lengths
 Â           #  Bifurcate; short for Duplicate & Reverse copy
  ‚          #  Pair the two together
   ε         #  Map over each pair of lists:
    `        #   Pop and push the two lists separated to the stack
     н       #   Pop and push the first pair of the top lists,
             #   which is the attacking animal
      U      #   Pop and store this pair in variable `X`
     ć       #   Extract head on the other list; push remainder-list and first
             #   item separated to the stack, which is the animal that's being
             #   attacked
      X      #   Push the attacking animal-pair from variable `X`
       R     #   Reverse its [ATK,HP] to [HP,ATK]
        0Dǝ  #   Replace its HP (at index 0) with 0: [0,ATK]
           - #   Subtract this from the animal that's being attacked
     W       #   Push the minimum of this animal (without popping)
      1@i    #   If it's >=1 (so the animal is still conscious):
         š   #    Prepend it back to the list
        ë    #   Else:
         \   #    Discard the unconscious animal from the stack
]            # Close the if-statement and loop
 `           # Pop and push the lists separated to the stack
  .S         # Compare the two lists (-1 if a<b; 0 if a==b; 1 if a>b)
             # (which is output implicitly as result)

```

# Answer
> 2 votes
# Desmos, ~~124~~ 123 bytes

```
a->f(a,b),b->f(b,a)
a=\ans_1
b=\ans_2
o=sign(a.length-b.length)
k=B[1].x
f(A,B)=\join(\{A[1].y>k:[A[1]-(0,k)],[]\},A[2...])

```

Exits upon error. Output is `o`, with its value being `-1` if `B` wins, `0` if tie, and `1` if `A` wins.

Input is two lists of points. The graphs will further specify how to input the lists.

I had a lot of fun solving this in Desmos! Actions are super fun to mess around with, and this was the perfect challenge to showcase that.

Try It On Desmos!

Try It On Desmos! - Prettified

### Explanation

I'm going to explain the expressions a little out of order so that it makes more sense. I don't know why I didn't order it properly initially but whatever.

---

```
a=\ans_1
b=\ans_2

```

Takes in input.

```
k=B[1].x
f(A,B)=\join(\{A[1].y>k:[A[1]-(0,k)],[]\},A[2...])

```

This function essentially simulates one "half-turn" of the game. By "half-turn", I mean one of the teams attacking the other. In this case, the inputs are the lists `A` and `B` representing the teams of the same name, and it will simulate team `B` attacking team `A`.

`k=B[1].x` is the attack of the first animal on team `B`.

`\{A[1].y>k:[A[1]-(0,k)],[]\}` basically means: if the health of the first animal on team `A` (`A[1].y`) is greater than `k`, then return the list `[A[1]-(0,k)]`, which simulates team `A`'s first animal taking `k` damage. If `A[1].y>k` is false, then that means the first animal on team `A` does not survive the hit, so we return an empty list to represent that. You might be wondering why we have to return a list for `[A[1]-(0,k)]` instead of a number, since you can join a number with a list. This is because of Desmos's underlying vectorization for almost anything that you do with lists. In this case, if I had just returned `A[1]-(0,k)` instead of `[A[1]-(0,k)]`, then Desmos will vectorize the entire piecewise expression based on the empty list, which will, in turn, always make the piecewise expression equal to an empty list. By making the number into a list, we avoid this issue completely and it behaves as expected.

`f(A,B)=\join( . . . ,A[2...])`: The newly calculated stats of the first animal of team `A` is then prepended with the rest of `A`. The function `f(A,B)` returns this updated list.

```
a->f(a,b),b->f(b,a)

```

The ticker runs these actions continually, which simulates the game, updating the input lists in place.

`a->f(a,b)`: Team `b` attacks team `a` and updates list `a` after the attack.

`b->f(b,a)`: Team `a` attacks team `b` and updates list `b`. Conveniently, the value of `a` used in this action is actually the old value of `a` before the attack on team `a` (`a->f(a,b)`) occurred, which essentially simulates the two teams attacking each other at the same time. If it used the newly updated `a`, then it would be harder to simulate the attacks as you would most likely need to keep track of list `a` before the attack, so that you can accurately apply the attack on team `b` (or else it would be team `b` attacks team `a`, then team `a` attacks team `b`, instead of attacking at the same time).

Once at least one of the lists becomes empty, then the ticker errors out, because when calling the function `f(A,B)`, either `A[1]` or `B[1]` would be undefined because one of them would be empty, which will cause `A[1].y` or `B[1].x` to throw an error. When the ticker throws an error, we will know that the game is over, since the error indicates that one or both teams have no more animals.

```
o=sign(a.length-b.length)

```

Returns the final output. If `a.length > b.length` (indicates that `a` wins), then `a.length-b.length` will be positive, so `o=1`. If `a.length < b.length` (indicates that `b` wins), then `a.length-b.length` will be negative, so `o=-1`. If `a.length = b.length` (indicates that it was a tie), then `a.length-b.length` will be `0`, so `o=0`.

---
Tags: code-golf, game, simulation
---


title: The interstice of two binary numbers

text:
# Question
Title: The interstice of two binary numbers
Given two integers, compute the two numbers that come from the blending the bits of the binary numbers of equal length(same number of digits, a number with less digits has zeros added), one after the other, like such:

```
2 1
10 01
1 0
1001
0 1
0110

```

some examples:

| Input | Binary | Conversion | Output |
| --- | --- | --- | --- |
| 1,0 | 1,0 | 10,01 | 2,1 |
| 1,2 | 01,10 | 0110,1001 | 6,9 |
| 2,3 | 10,11 | 1101,1110 | 13,14 |
| 4,9 | 0100,1001 | 01100001,10010010 | 97,146 |
| 12,12 | 1100,1100 | 11110000,11110000 | 240,240 |
| 1,3 | 01,11 | 0111,1011 | 7,11 |
| 7,11 | 0111,1011 | 01101111,10011111 | 111,159 |
| 7,3 | 111,011 | 101111,011111 | 47,31 |

The program must take integers as inputs and give integers as outputs

# Answer
> 7 votes
# Jelly,  ~~8~~  6 bytes

-2 Thanks to Unrelated String!

```
Bḅ4S+$

```

A monadic Link that accepts a pair of non-negative integers and yields a pair of non-negative integers.

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

### How?

```
Bḅ4S+$ - Link: integers A           e.g. [4, 9]
B      - convert A to binary             [[1,0,0],[1,0,0,1]]
 ḅ4    - convert from base 4             [16,65]
                                 ...i.e. insert zeros between the binary digits
                                         [16,65] = [[1,0,0,0,0],[1,0,0,0,0,0,1]]
     $ - last 2 links as a monad - f(x):
   S   -   sum x                         81
    +  -   add x (vectorises)            [97,146]
                                 ...i.e. the above S+$ is a rearrangement of
                                         [(16+16)+65,(65+65)+16]
                                         where 16+16 is the zero spaced bits of 4
                                         shifted one place to the left & similarly
                                         for (65+65) with respect to 9.

```

# Answer
> 6 votes
# APL (Dyalog Extended), 9 bytes

```
,⍥⊥⍥,∘⌽⍨⊤

```

Try it online!

Create a matrix where each column holds a binary representation of one of the integers.
`f∘⌽⍨` Apply the function `f` with that matrix on the left and the reverse of the matrix on the right.
`,⍥⊥⍥,` Flatten both matrices, convert both resulting vectors from binary and pair them up to return a length-2 vector of integers.

Alternatively, for a bit more symmetry: `⊤,⍥⊥⍥,⌽⍤⊤`

# Answer
> 6 votes
3 versions, all work in 32 or 64-bit mode:
x86 machine code (clmul + AVX-512), 17 bytes. (Or 16B with AMD XOP instead of AVX-512)
x86 machine code (clmul + AVX1 32-\>64-bit, output pair in same order as input pair), 18 bytes
x86 scalar machine code (with BMI2 `pdep`), 22 bytes

# x86 machine code (clmul + AVX-512), 17 bytes

Takes 2 integers in the low two 16-bit elements of XMM0, returns 2 integers in 32-bit elements #1 and #0 of XMM0 (in that order, opposite of the input order). Swapping them would take another 4-byte instruction, `shufps xmm0, 0b00_01` (or a left shift of the original and a different rotate count), but if we're willing to stretch the bounds of calling-convention plausibility, this is fine. If not, use the 18 byte version below.

NASM listing: address, hexdump of machine code, source

```
;;; 16-bit inputs packed in XMM0,  32-bit outputs packed in XMM0 (opposite order)
                        bit_interleave_bothways_avx512:
00 C4E37944C000     vpclmulqdq  xmm0, xmm0, 0      ; space out each bit
                      ;    movq       rax, xmm0
                      ;    rol        rax, 33      ; non-AVX512 emulation for the low qword
                      ;    movq       xmm1, rax
06 62F1F50872C821   vprolq     xmm1, xmm0, 33      ; <<=1 and swap 32-bit halves
0D 0F56C1           orps       xmm0, xmm1          ; combine
10 C3               ret

```

Key building block: Carryless multiply of a number by itself spaces out the bits, interleaving with zeros. x86 has that as `pclmulqdq`, single-uop on modern Intel, e.g. Skylake (and 4 uops on AMD Zen1/2/3). Same size for VEX or legacy-SSE encoding, 6 bytes. With an immediate `0`, reads the low qword of each input, writes a 128-bit output to the full dqword XMM register.

AVX-512 has SIMD rotates, but unfortunately earlier Intel doesn't. (TODO: **AMD's XOP instruction set has `vprotq`** with a 6-byte encoding according to NASM, 1 shorter than AVX-512 EVEX. AFAIK equivalent behaviour with an immediate count of 33. Would only run on AMD Bulldozer-family, which I don't have, so would be inconvenient to test but would still satisfy the rules of working on at least one implementation of a language.)

Combining the swap to line up outputs with each other along with a shift by 1 bit can be done with one rotate, but only with an EVEX encoding (4-byte prefix + opcode + modRM + imm8 = 7-byte encoding.) And only within a 64-bit qword, which means limiting the output size to two 32-bit integers, which means limiting the input to 16-bit integers.

Legacy SSE1 encodings are the smallest, only the escape byte no mandatory prefixes. We didn't dirty any YMM upper halves, so there's no SSE/AVX transition penalty here from mixing VEX/EVEX with legacy SSE. `vorps xmm0, xmm0, xmm1` or `por xmm0, xmm1` would each be 4 bytes.

# x86 machine code (clmul 32-\>64-bit), 18 bytes

Requires only AVX1 + CLMUL CPU features, e.g. Sandybridge.

As above with `clmul`, but using separate left-shift and swapping halves of the output to line them up for OR. This way we can handle 32-bit inputs (and the corresponding 64-bit outputs), and output in the same order as inputs.

Includes comments that trace the 4,9 test-case through it, confirmed from actual single-stepping in GDB. Would have output in hex, but the test cases strangely use decimal despite this being about bit-manipulation.

```
                        bit_interleave_bothways_avx512_32it:
                                                 ; xmm0.v4_int32 = { 4, 9, 0, 0}
30 C4E37944C000    vpclmulqdq  xmm0, xmm0, 0     ; xmm0.v2_int64 = { 16, 65 }  value after clmul, from GDB
36 C5F9D4C8        vpaddq      xmm1, xmm0, xmm0           ; xmm1 = { 32, 130 }  ; VEX allows copy + left-shift with same size as paddw
3A 0FC6C04E        shufps      xmm0, xmm0, 0b01_00_11_10  ; xmm0 = { 65, 16 }
3E 0F56C1          orps        xmm0, xmm1                 ; xmm0 = { 97, 146 }  ; in-place swap saves a byte vs. pshufd
41 C3              ret

```

Two 4-byte instructions (`vpaddq` and `shufps`) are only 1 byte larger than a single 7-byte EVEX `vprolq`.

---

# x86 scalar machine code (with BMI2), 22 bytes

```
                bit_interleave_bothways:
00 BA55555555     mov   edx, 0x55555555
05 C4E243F5FA     pdep  edi, edi, edx
0A C4E24BF5F2     pdep  esi, esi, edx
0F 8D047E         lea   eax, [rsi + rdi*2]  ; low bit = low b of arg1 = first out
12 8D1477         lea   edx, [rdi + rsi*2]  ; low bit = low b of arg2 = second out
15 C3             ret

```

Callable with the x86-64 System V calling convention (args in EDI, ESI),
return values in EAX (first), EDX (second).

The output is only 32 bits wide. This limit is more justifiable in 32-bit mode, where the same machine code does the same thing, disassembling as `lea eax, [esi + edi*2]` and so on. (Using 64-bit operand-size would cost an extra REX.W byte on each PDEP and LEA, and need a 10-byte `mov rdx, 0x5555555555555555` instead of 5-byte `mov reg, imm32`, so an extra 9 bytes total). The same machine code would *not* work in 16-bit mode; scaled index addressing modes would need an address-size prefix. VEX prefixes (for `pdep`) only decode in 16-bit protected mode, not real.

The key building block is `pdep`, parallel bit-deposit, which takes low source bits and puts them at places where the control mask was non-zero. With `0b...010101`, this unpacks each input by interleaving it with zeros.

Doing `(x << 1) + y` and vice versa with LEA merges the unpacked bits into a single interleaved integer. `+` instead of the more idiomatic `|` allows using the shift-and-add LEA instruction.

Try it online! with a brief test harness. (Only uses the first return value as exit status; I tested by single-stepping in a debugger. Not updated for the later CLMUL versions.)

# Answer
> 5 votes
# C (clang), <sup>~~91~~</sup> 86 bytes

```
i;t;f(*a,*b){for(i=1<<17;i/=2;*b=*b&~i|(*b&i)*i)t=*a=*a&~i|(*a&i)*i;*a+=*b*2;*b+=2*t;}

```

Try it online!

*Saved 5 bytes thanks to Olivier Grégoire!*

Inputs pointers to two integers.
Returns the Interleaved Values™ (Neil) through the input pointers.

# Answer
> 5 votes
# Vyxal, 7 bytes

```
b4vβ:∑+

```

Try it Online!

Port of (my suggested golf to) Jonathan Allan's Jelly solution. Input as a list of the two numbers.

```
b          Convert each to binary,
 4vβ       then convert each from base 4.
b4vβ       This has the effect of interleaving with a bit pattern of all zeroes.
      +    Add each to
    :∑     their sum.

```

# Answer
> 4 votes
# Python, 54 bytes (@UnrelatedString)

```
lambda*I:map(sum,2*[J:=[int(f"{x:b}",4)for x in I]],J)
```

Attempt This Online!

### Old Python, 57 bytes

```
lambda*I:[*map(sum,2*[J:=[int(f"{x:b}",4)for x in I]],J)]
```

Attempt This Online!

# Answer
> 4 votes
# Wolfram Language (Mathematica), 41 bytes

```
If[#1,0,Tr[a=#~Mod~2]+a+4#0[(#-a)/2]]&

```

Try it online!

# Answer
> 4 votes
## x64 machine code (requires VPCLMULQDQ, supported by Intel Ice Lake and later), ~~22~~ 21 bytes

Totally different approach than the BMI2 solution, ~~but by some cosmic coincidence it's exactly the same size~~, well it was until I saved a byte.

```
0:  c4 e3 7d 44 c0 00       vpclmullqlqdq ymm0,ymm0,ymm0
6:  c4 e3 fd 00 c8 4e       vpermq ymm1,ymm0,0x4e
c:  c5 f5 d4 c9             vpaddq ymm1,ymm1,ymm1
10: c5 f5 eb c0             vpor   ymm0,ymm1,ymm0
14: c3                      ret

```

Takes the input in a slightly odd way: a 256-bit vector with a 64bit number at index 0 and at index 2, the rest just padding. Maybe cheating?

Output is in a 256-bit vector again, but since it's two *128-bit* numbers, that doesn't feel like cheating to me.

The idea here is that a carryless square is equivalent to spacing the bits out just like we need here, so the first step is to carrylessly-multiply the input with itself. Then `vpermq` is used to get a copy of the squares but with the low and high halves switched around, `vpaddq` shifts that all left by 1, and `vpor` merges the even and odd bits together.

If you want to try this code, beware: there's a high chance your processor doesn't support this `vpclmulqdq` instruction. It was introduced with Intel's Ice Lake microarchitecture and is also supported by Tiger Lake and Rocket Lake. It is not officially supported on Alder Lake, but can be enabled on certain systems. Since this instruction is not officially part of AVX-512, it may not be present in future implementations.

# Answer
> 3 votes
# JavaScript, 55 bytes

```
q=v=>v&&q(v>>1)*4+v%2,a=>a.map((x,i)=>q(x)*2+q(a[i^1]))

```

Try it online!

# Answer
> 3 votes
# Java (JDK), 89 bytes

```
(l,r)->{for(int i=1<<16;i>0;r=r&~i|(r&i)*i,i/=2)l=l&~i|(l&i)*i;return r+l*2+","+(l+r*2);}

```

Try it online!

This first interweaves 0 between each bit of each number, then weaves the two numbers together in both directions.

# Answer
> 2 votes
# Pip, 22 bytes

```
L2PFB R J:R*TB(R:g)ZD0

```

Takes the two numbers as command-line arguments. Attempt This Online!

### Explanation

```
L2PFB R J:R*TB(R:g)ZD0
L2                      Loop twice:
               R:         Reverse in-place
                 g        The list of command-line args
            TB(   )       Convert each to binary
          R*              Reverse each binary representation
                   ZD0    Zip, filling in missing values with 0
        J:                Join into a single string of 1s and 0s
      R                   Reverse
   FB                     Convert from binary back to decimal
  P                       Print

```

# Answer
> 2 votes
# Charcoal, ~~16~~ 14 bytes

```
Ｆ²⊞υ↨⁴↨Ｎ²Ｉ⁺Συυ

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @UnrelatedString. Explanation:

```
Ｆ²⊞υ↨⁴↨Ｎ²

```

Input the two integers, convert them to base `2`, and then convert them from base `4`. This spaces the bits in the integers out.

```
Ｉ⁺Συυ

```

Vectorised add the list to its doubled sum. This interleaves the bits in both ways.

Example: With inputs of `4` and `9`, these are `0100` and `1001` in binary, and spaced out these are `00010000` and `01000001`. Adding the sum of these to each results in `00010000+00010000+01000001` and `00010000+01000001+01000001`, which is equivalent to `00100000+01000001` and `00010000+10000010`, resulting in `01100001` and `10010010`, which are the desired interleaved values.

# Answer
> 2 votes
# PARI/GP, 35 bytes

```
f(a)=if(a,4*f(a\2)+a%2*[2,1;1,2],a)
```

Takes input as a vector of two integers.

Attempt This Online!

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
b4öDO+

```

I/O as a pair of integers.

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

Try it online or verify all test cases.

**Explanation:**

```
b       # Convert both integer in the (implicit) input-pair to binary strings
 4ö     # Convert them from base-4 strings back to integers
   D    # Duplicate this pair of integers
    O   # Sum them together
     +  # Add this sum to both values
        # (after which the resulting pair is output implicitly)

```

# Answer
> 2 votes
# Desmos, ~~94~~ 87 bytes

```
f(a,b)=[g(a),g(b)]+g(a)+g(b)
g(A)=total(mod(floor(A/2^k),2)4^k)
k=[0...log_2(A+0^A)+.5]

```

Uses the base-4 interleaving trick that some of the other answers are using. Not sure if this is the optimal strategy for Desmos though, I will definitely look at alternate strategies.

The `+.5` trick works on the last line because if the end of an arithmetic range is not an integer, it will round it instead. For example, `[1...3.5]` is the same as `[1...4]`, while `[1...3.4]` is the same as `[1...3]`. We take advantage of the implicit rounding by noting that round(x-.5) is equal to floor(x), so we can convert `[0...floor(log_2(A+0^A))+1]` to `[0...log_2(A+0^A)+.5]`.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Factor, 59 bytes

```
[ [ 64 <bits> ] bi@ 2dup swap [ vmerge bits>number ] 2bi@ ]

```

Try it online!

* `[ ... ] bi@` Call a quotation on two objects.
* `64 <bits>` Convert an integer to a virtual sequence of sixty-four booleans.
* `2dup swap` Set up the data stack for both interleavings. `a b -> a b b a`
* `[ ... ] 2bi@` Call a quotation on two pairs of objects.
* `vmerge` Interleave two sequences.
* `bits>number` Convert a boolean sequence to an integer.

# Answer
> 1 votes
# ARMv8.2 A64 machine code (requires FEAT\_SHA3), 16 bytes

```
0e20e000 6e004001 ce608c20 d65f03c0

```

Following the AAPCS64, this takes a `uint32x2_t` in the low half of v0 and returns a `uint64x2_t` in v0.

Disassembled:

```
0e20e000    pmull   v0.8h, v0.8b, v0.8b
    // Self-multiply as polynomials over GF(2);
    // because this is a ring of characteristic 2, (a+b)^2 = a^2 + b^2 holds,
    // thus squaring doubles each exponent in the polynomial, spreading out the bits.
6e004001    ext v1.16b, v0.16b, v0.16b, #8
    // Extract bytes 8–23 from the concatenation of v0 and v0, and put them into v1.
    // This swaps the positions of the two 64-bit numbers.
ce608c20    rax1    v0.2d, v1.2d, v0.2d
    // Rotate each 64-bit element of v0 left by 1
    // and then take the exclusive-or with v1, and put the result in v0.
d65f03c0    ret
    // Return.

```

---
Tags: code-golf, number, integer, binary
---


title: Remove unmatched brackets

text:
# Question
Title: Remove unmatched brackets
Inspired by @AviFS.

Given a string containing brackets, e.g.

```
[xyz]]abc[[def]hij[

```

You can parse through it with a stack of brackets. When you find an open bracket, push a value to the stack, when you find a close bracket, pop from the stack. If you make these values indices, you know where you need to remove brackets.

If you try to pop from an empty stack, the close bracket is unmatched, and the brackets left on the stack at the end are unmatched.

For example, the above would be:

```
[                   # PUSH index 1 - [1]
 xyz]               # POP - []
     ]              # POP from empty stack, unmatched
      abc[          # PUSH index 4 - [4]
          [         # PUSH index 5 - [4, 5]
           def]     # POP - [4]
               hij[ # PUSH index 7 - [4, 7]

```

After doing this, the 3rd bracket is unmatched as it pops from an empty stack, and the 4th and 7th brackets are unmatched as they were left on the stack.

Here's another way of viewing the matching:

```
     **]**abc**[**
[   ]     [   ]hij**[**
 xyz       def

```

Your challenge is to remove those unmatched brackets, leaving matched ones alone. For the above:

```
[   ]abc[   ]hij
 xyz     def

```

You may use any pair of brackets out of `()`, `[]`, `{}`, and `<>`, and the input will only contain those and lowercase letters.

## Testcases

```
[abc -> abc
[[] -> []
a[x[y]z[e]k[ -> ax[y]z[e]k
]ab[cdef]]gh[ij[klm]no]] -> ab[cdef]gh[ij[klm]no]

```

# Answer
# JavaScript (Node.js), 94 91 89 78 bytes

```
f=s=>s==(t=s.replace(/<(\w*)>/,"0$11"))?s.replace(/[^a-z]/g,x=>['<>'[x]]):f(t)

```

Try it online!

*-2 thanks to ophact*

*-11 thanks to Arnauld: When returning an array in the `replace` callback function, `undefined` values will be deleted. Eg, `'abcde'.replace(/b/,x=>['<>'[x]])` returns `acde`*

~~Am curious to see how this can be improved...~~

We use `<>` for our bracket characters.

Approach:

* Replace valid instances of `<...>` with `0...1` until it stops changing.
* Remove remaining `<>` characters.
* Map `01` back to `<>`.
    + This part could probably be golfed better. It amounts to finding a JS golf for `tr`. Currently we use the match (`0` or `1`) to index into `<>`, which is shorter than doing two replaces.
> 6 votes

# Answer
# Ruby `-p`, ~~37~~ ~~29~~ 28 bytes

```
$_=$_.scan(/<\g<0>*>|\w/)*''

```

Try it online!

Uses `<>` as brackets. Scans for, and prints:

* paired brackets and anything between them,
* letters outside brackets.

`\g<0>` embeds the regex within itself, allowing us to match nested bracket pairs recursively.
> 6 votes

# Answer
# Retina 1, 35 bytes

```
|""L`<((<)|(?<-2>>)|\w)*(?(2)^)>|\w

```

Try it online! Link includes test cases. Uses `<>` as brackets. Explanation: `|""L`` indicates that Retina should list the matches without a separator, the matches being any paired bracket string or letter.
> 3 votes

# Answer
# Jelly, 26 bytes

```
¬Ø[iⱮT,ƝịJƑ¥ƇƊFƲ¦ÐLe€Ø[oḟ1

```

A monadic Link that accepts a list of characters and yields a list of characters.

**Try it online!**

### How?

Finds any `"[...]"` where the middle has no `'['` or `']'` and replaces the `'['` and `']'` with zeros. Repeats that until no change happens. Checks each value in the result for existence in `"[]"`, giving a list of zeros and ones where the ones identify any `'['` or `']'` to remove. Logical ORs these with the input characters, to give a list of ones and characters, and then removes the ones.

```
¬Ø[iⱮT,ƝịJƑ¥ƇƊFƲ¦ÐLe€Ø[oḟ1 - Link: list of characters
                 ÐL        - loop while distinct applying:
                ¦          -   sparse application...
¬                          -   ...of: logical NOT (i.e. replace with a zero)
               Ʋ           -   ...to indices: last 4 links as a monad - f(Current):
 Ø[                        -     "[]"
    Ɱ                      -     map across c in Current with:
   i                       -      first 1-indexed index of c in "[]" or 0
                                     e.g. "]ab[c]d[" -> [2,0,0,1,0,2,0,1]
             Ɗ             -     last 3 links as a monad - f(X=that):
     T                     -       truthy indices       [1,4,6,8]
       Ɲ                   -       for neighbours:
      ,                    -         pair               [[1,4],[4,6],[6,8]]
            Ƈ              -       keep those for which:
           ¥               -         last 2 links as a dyad - f(Neighbours, X)
        ị                  -           Neighbours index into X (vectorises)
          Ƒ                -           is invariant under?:
         J                 -             range of length
                                       (i.e. =[1,2]? hence outer indices of "[...]"
                                        with no '[' or ']' in the middle)
              F            -     flatten -> indices of some valid []s
                     Ø[    - "[]"
                    €      - for each value in the loop result:
                   e       -   exists in "[]"?
                       o   - logical OR with the input (vectorises)
                         1 - one
                        ḟ  - filter - discard ones

```
> 3 votes

# Answer
# Retina 0.8.2, ~~65~~ 28 bytes

```
+T`<>`{}`<[^<>]*>
T`{}<>`<>_

```

Try it online! Link includes test cases. Uses `<>` as brackets. Explanation: Port of @Jonah's JavaScript answer.

```
+`

```

Repeat until no more transliterations can be made.

```
T`<>`{}`<[^<>]*>

```

Transliterate `<>` to `{}` if it's a matched pair that doesn't contain inner `<>`s (but it can include inner `{}` that were previously matched and transliterated).

```
T`{}<>`<>_

```

Transliterate `{}` back to `<>` but delete any remaining `<>` first.

A Replace stage can also be used for the first step for the same byte count:

```
+`<([^<>]*)>
{$1}
T`{}<>`<>_

```

Try it online! Link includes test cases.

Previous 65-byte answer deleted mismatched `<>`s directly:

```
(?<!<(?(2)$)((>)|(?<-2><)|\w)*)>|<(?!((<)|(?<-4>>)|\w)*(?(4)^)>)

```

Try it online! Link includes test cases. Uses `<>` as brackets. Explanation: Uses lookarounds and .NET balancing groups to directly match and delete unpaired brackets. Note that the lookbehind matches from right-to-left so the three parts are in the opposite order to the lookahead.
> 2 votes

# Answer
# Python3, 136 bytes:

```
import re
f=lambda x:x.translate(str.maketrans({'{':'[','}':']','[':'',']':''}))if x==(x:=re.sub('\[([\w\{\}]+)*\]','{\\1}',x))else f(x)

```

Try it online!
> 1 votes

# Answer
# Charcoal, 37 bytes

```
ＦＳ¿⁼<ι⊞υω«Ｆ⁼>ι≔⎇υ⪫<>⊟υωι¿υ⊞υ⁺⊟υιι»⪫υω

```

Try it online! Link is to verbose version of code. Uses `<>` as brackets only because that's what I used for my Retina answers. Explanation:

```
ＦＳ

```

Start by tokenising the input string into characters and loop over them.

```
¿⁼<ι⊞υω«

```

If the next token is a `<`, then push an empty string to the stack, representing the characters waiting to be wrapped in `<>`s. Otherwise:

```
Ｆ⁼>ι≔⎇υ⪫<>⊟υωι

```

If the next token is a `>` then if the stack is empty then set the token to the empty string otherwise pop the balanced string from the stack and wrap it in `<>`s.

```
¿υ⊞υ⁺⊟υιι

```

If the stack is (now) empty then print the current balanced string otherwise append it to the top balanced string of the stack.

```
»⪫υω

```

Print any balanced string parts which were waiting to be wrapped in `<>`s but their closing `>`s were missing.
> 1 votes

# Answer
# , ~~89~~ 86 bytes

```
f=\(x,`[`=gsub)"if"(x!=(x="<([^<>]*)>"["L\\1R",x]),f(x),chartr("LR","<>","<|>"["",x]))
```

Attempt This Online!

Port of @Jonah's JS answer.

Uses `<>` as brackets and `LR` as intermediate replacement (to lower confusion with `[]` in already two other contexts).

Slightly longer, but a probably more interesting attempt with the use of `Reduce`:

**, 91 bytes**

```
\(x,`[`=gsub)chartr("LR","<>","<|>"["",Reduce(\(a,b)"<([^<>]*)>"["L\\1R",a],1:nchar(x),x)])
```

Attempt This Online!
> 1 votes

# Answer
# PARI/GP, 92 bytes

```
s->strjoin(g(g(s,"[","]"),"]","["))
g(s,l,r,i)=[c|c<-Vecrev(s),c==r&&i++||c!=l||i-->=0||i=0]

```

Attempt This Online!
> 1 votes

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


title: Who will win the election?

text:
# Question
Title: Who will win the election?
This is a challenge in which two people, 1 and 2, are running for office. People deterministically vote in certain ways in the world of 1 and 2, which can allow for the candidates to figure out the results before the election.

NOTE: this is not meant to refer to any outside elections or other political events.

Two people are running for office. We'll call these people 1 and 2. Because they both want to know if they will win the election, they decide to use their knowledge of people and some code to figure out what the result will be. Due to the want to minimize government spending, the code needs to be a short as possible.

**Your task:** Given a string of people based on how they are voting, output who wins the election.

There are five kinds of people in the fun and exciting world of 1 and 2:

* `A`: people who will definitely vote for 1.
* `B`: people who will definitely vote for 2.
* `X`: people who will vote for whoever the person to their left will vote for. If there is no person to their left, then they vote for whoever the person at their right will vote for. If it is not clear who the person to their right is voting for, then they do not vote.
* `Y`: people will vote the opposite of the person to their left. If there is no person to their left, then they vote opposite of whoever is at their right. If it is not clear who the person to their right is voting for, then they do not vote.
* `N`: people who do not vote.

This is evaluated from left to right.

**Example:**

Whoever is being "evaluated" is in lowercase, for clarity.

```
Input: `XXAYAN`
        xX      Votes for whoever their friend is voting for. Their friend has not decided yet, so it is unclear, so they do not vote.
        Xx      Person to left is voting "none" so votes "none."
          a     Votes for 1
          Ay    Since person on left is voting for 1, votes for 2.
            a   Votes for 1
             n  Does not vote

```

Final poll:

* 2 people voted for 1
* 1 people voted for 2
* 3 people did not vote

1 has the most votes, so 1 wins!

**Test cases:**

You may use other characters or values as input and output, as long as they are distinct. (For example: numbers instead of letters, different letters, lowercase letters, truthy/falsy or positive/negative (for output), etc.)

```
Input -> Output

"AAAA" -> 1
"BBBB" -> 2
"BBAXY" -> 2
"BAXYBNXBAYXBN" -> 2
"XXAYAN" -> 1
"AAAABXXXX" -> 2
"AXNXXXXAYB" -> 1
"NANNY" -> 1
"XA" -> 1
"YAB" -> 2
"XY" -> anything (do not need to handle test cases with no victor)
"AB" -> anything (do not need to handle test cases with no victor)

```

# Answer
# Java 8, ~~153~~ ~~141~~ ~~135~~ ~~131~~ 129 bytes

```
a->{int l=a.length,t,r=0,i=-1;for(;++i<l;r+=(t=a[i]=a[i]>4?t<3?t^3:3:a[i]>3?t:a[i])>2?0:3-t*2)t=a[i>0?i-1:i<l-1?i+1:i];return r;}

```

Uses an integer array as input with `A=1, B=2, N=3, X=4, Y=5` and outputs a positive integer (`>= 1`) if A wins, a negative integer (`<= -1`) if B wins, or `0` if it's a draw.

-18 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
a->{                      // Method with int-array parameter and boolean return-type
  int l=a.length,         //  Length of the input-array
      t,                  //  Temp integer, uninitialized
      r=0,                //  Result-integer, starting at 0
  i=-1;for(;++i<l         //  Loop `i` in the range [0, l):
           ;              //    After every iteration:
            r+=           //     Increase the result by:
             (t=a[i]=     //       Change `i`'th item in the array to:
                 a[i]>4?  //        If the `i`'th item is a 5:
                  t<3?    //         If `t` is 1 or 2:
                   t^3    //          Use `t` Bitwise-XOR 3 to invert it
                          //          (1 becomes 2; 2 becomes 1)
                  :       //         Else (`t` is 3, 4, or 5 instead):
                   3      //          Set it to 3
                 :a[i]>3? //        Else-if the `i`'th item is a 4:
                  t       //         Set it to `t`
                 :        //        Else (the `i`'th item is a 1, 2 or 3):
                  a[i])   //         Leave it unchanged
             )>2?         //      And if this new `i`'th value is 3, 4, or 5:
              0           //       Leave the result the same by increasing it with 0
             :            //      Else (it's 1 or 2 instead):
              3-t*2;      //       Increase it by 3 minus two times the `i`'th value
                          //       (which is 1 for 1; and -1 for 2)
         t=               //   Set `t` to:
           a[i>0?         //    If `i` is not the first item:
              i-1         //     Set `t` to the previous (`i-1`'th) value
             :i<l-1?      //    Else-if `i` is not the last item:
              i+1         //     Set `t` to the next (`i+1`'th) value
             :            //    Else (`i` is the first or last item):
              i];         //     Set `t` to the current item itself
  return r;}              //  Return the result
                          //  (positive if A wins; negative if B wins; 0 if it's draw)

```
> 9 votes

# Answer
## Haskell, ~~60~~ ~~50~~ ~~48~~ 59 bytes

```
l#(v:o)|v<2=v+v#o|n<-(3-v)*l=n+n#o
_#_=0
f x=rem(x!!1)2#x>0

```

Uses `1` for `A`, `-1` for `B`, `0` for `N`, `2` for `X` and `4` for `Y`. Returns `True` if `A` wins, else `False`.

Try it online!

On the recursive way down the input list we add `1` for every vote for `A`, `-1` for every vote for `B` and `0` for "no vote". `l` is the last vote, `v` the next. If `v=1`, `-1` or `0` (or `v<2`) we just add it to the sum. If `v` is "vote same" (`X` in the challenge, `2` for my solution) we keep and add `l` (`(3-2)*l` = `l`). If `v` is "vote opposite" (`Y` in the challenge, `4` for my solution) we first negate `l` (`(3-4)*l` = `-l`) and then add it. Base case is the empty list which starts the sum with `0`. Recursion is started with `l` set to `rem s 2` where `s` is the second element of the input list (`x!!1`). `rem s 2` maps `1` and `-1` to itself, all other values to `0`. Fix votes ignore `l` anyway \[\*\] and `X` or `Y` get the right neighbor if it's a fix vote. If the overall sum is positive, `A` wins.

\[\*\] this makes singleton lists with fix votes like `[1]` work, because due to Haskell's laziness access to the second element is never evaluated. Inputs like `[2]` fail with error, but don't have to be considered.
> 8 votes

# Answer
# Perl 5, ~~56~~ ~~80~~ ~~72~~ ~~65~~ 53 bytes

+26 bytes to handle the case X or Y in first position and A or B in second. output is `1` if 1 wins empty (false value in perl) otherwise.

```
s/^X(.)/$1$1/,s/A\KX|B\KY|^Y(?=B)/A/|s/B\KX|A\KY|^Y(?=A)/B/&&redo;$_=y/A//>y/B//

```

TIO

using `P` and `S` instead of `X` and `Y` allowing to use xor operation on characters, would save some more bytes

```
s/(?|^(P|S)(?=(A|B))|(A|B)\K(P|S))/P^$1^$2/e&&redo;$_=y/A//>y/B//

```

uses a branch reset group `(?|`..`|`..`)`, so that `$1` `$2` refering to corresponding group in branch. Using `\0` and `\3` instead of `X` and `Y`

```
$_=s/^\W(?=(\w))|(\w)\K\W/$1.$2^$&/e?redo:y/A//>y/B//

```

72 bytes

65 bytes

53 bytes
> 8 votes

# Answer
# JavaScript (ES6),  ~~78 75~~  73 bytes

Takes input as an array of integers with: \\$0\\$ = N, \\$1\\$ = A, \\$2\\$ = B, \\$4\\$ = Y, \\$8\\$ = X.

Returns \\$false\\$ if the first candidate wins or \\$true\\$ if the 2nd candidate wins.

```
a=>a.reduce((v,x,i)=>v+~~[,1,-1][p=x?x&3||~-x%7^(p&3||a[i+1]&3):0],p=0)<0

```

Try it online!
> 6 votes

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

```
gFÐNè©2@iNx1.S-èDÄ2‹*D(‚®èNǝ]O

```

Uses an integer-array as input with `A=-1, B=1, N=0, X=2, Y=3` and outputs a negative integer (`<= -1`) if A wins, a positive integer (`>= 1`) if B wins, or `0` if it's a draw.

Try it online or verify all test cases.

**Explanation:**

```
g             # Take the length of the (implicit) input-list
              #  i.e. [3,1,3,3,2,0,1] → 7
 F            # Loop `N` in the range [0, length):
  Ð           #  Triplicate the list at the top of the stack
              #  (which is the implicit input-list in the first iteration)
   Nè         #  Get the `N`'th item of the list
              #   i.e. [3,1,3,3,2,0,1] and `N`=0 → 3
              #   i.e. [-1,1,-1,3,2,0,1] and `N`=3 → 3
     ©        #  Store it in the register (without popping)
   2@i        #  If it's larger than or equal to 2 (so either 2 or 3):
      Nx      #   Push `N` and `N` doubled both to the stack
              #    i.e. `N`=0 → 0 and 0
              #    i.e. `N`=3 → 3 and 6
        1.S   #   Compare the double integer with 1 (-1 if N*2<1; 0 if N*2==1; 1 if N*2>1)
              #   (So this will be -1 in the first iteration, otherwise it will be 1)
              #    i.e. 0 → -1
              #    i.e. 6 → 1
           -è #   Subtract that from the index, and index it into the list
              #    i.e. `N`=0 and -1 → 1 (first item, so get the next index)
              #     → [3,1,3,3,2,0,1] and 1 → 1
              #    i.e. `N`=3 and 1 → 2 (fourth item, so get the previous index)
              #     → [-1,1,-1,3,2,0,1] and 2 → -1
      D       #   Duplicate that value
       Ä2‹    #   Check if that value is -1, 0, or 1 (abs(i) < 2) (truthy=1; falsey=0)
          *   #   And multiply that with the value
              #   (remains the same if truthy; or becomes 0 if falsey)
      D(‚     #   Pair it with its negative (-1 becomes [-1,1]; 1 becomes [1,-1])
         ®è   #   And index the `N`'th value (from the register) into it (with wraparound)
              #   (if it was a 2, it uses the unchanged (first) value of the pair;
              #    if it was a 3, it uses the negative (second) value of the pair)
              #     i.e. [1,-1] and 3 → -1
              #     i.e. [-1,1] and 3 → 1
      Nǝ      #   And replace the `N`'th value with this
              #    i.e. [3,1,3,3,2,0,1], `N`=0 and -1 → [-1,1,3,3,2,0,1]
              #    i.e. [-1,1,-1,3,2,0,1], `N`=3 and 1 → [-1,1,-1,1,2,0,1]
 ]            # Close both the if-statement and loop
  O           # Sum the modified list (which now only contains -1, 0, or 1)
              #  i.e. [-1,1,-1,1,1,0,1] → 2

```
> 5 votes

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

```
s=>s.map(c=>x+=l=c%2|l*c/2,l=s[x=1]%2)|x>1

```

Try it online!

Save 1 bytes, thanks to Shaggy.

---

* Input as integer array where N = 0, A = -1, B = 1, X = 2, Y = -2;
* Output 1 = Falsy, 2 = Truthy
> 5 votes

# Answer
# Python 2, ~~95~~ 73 bytes

```
lambda(v):sum([l for l in[2*int(v[1]/2)]for i in v for l in[i*l**(i%2)]])

```

Try it online!

---

* Input as integer array where N = 0, A = -2, B = 2, X = 1, Y = -1;
* Output negative = A, 0 = draw, positive = B
* If first input is X or Y, then 2\*int(v\[1\]/2) maps second to itself or 0

Bug fix was required that added extra bytes, but converting to lambda thanks to @Stephen reduced it back to 95
> 4 votes

# Answer
# Retina 0.8.2, 70 bytes

```
AY
AB
BY
BA
}`(A|B)X
$1$1
^X(A|B)|^Y[AB]
$1$1
+`N|X|Y|AB|BA

.+|(?<=B)

```

Try it online! Link includes test cases. Outputs `0` for a tie. Explanation:

```
AY
AB
BY
BA

```

Handle `Y` voters to the right of people with decided votes.

```
}`(A|B)X
$1$1

```

Handle `X` voters to the right of people with decided votes, and then loop back until all possible `Y` and `X` votes can be decided.

```
^X(A|B)|^Y[AB]
$1$1

```

Handle an initial `X` voter next to a decided vote, and also an initial `Y` voter next to a decided vote. As this voter will vote opposite to the decided vote, we can just delete both votes in this case.

```
+`N|X|Y|AB|BA

```

Delete any remaining no vote or undecided votes, and cancel out all pairs of opposing decided votes. Repeat until all possible votes are cancelled. In the case of a tie, nothing will be left, otherwise the remaining votes will all be of the same type.

```
.+|(?<=B)

```

Output `1` if there are any votes, but `2` if they are `B` votes.
> 3 votes

# Answer
# Python 3.8+, 55 bytes

```
lambda v:[l:=v[1]&~1]and sum((l:=i*l**(i%2))for i in v)
```

Attempt This Online!

Port of ABridgeTooFar's Python 2 solution, since we took the time in TNB to figure out why and how that list comprehension does anything at all.
> 3 votes

# Answer
## Python ~~3~~ 2, ~~125~~ ~~121~~ 117 bytes

(Thanks to Jonathan Frech)

```
def f(x):
    for i,v in enumerate(x):n=x[i-(i>0)];x[i]=(v>3)*n+abs(n-1)*(v<0)+x[i]*(0<v<4)
    print x.count(1)>x.count(0)

```

Using tab indentation

Input: list of `int`s where 'A'=1, 'B'=0, 'X'=4, 'N'=3, 'Y'=-1, so "AAAA" is `[1, 1, 1, 1]` and "XXAYAN" is `[4, 4, 1, -1, 1, 3]`.

`[{'A': 1, 'B': 0, 'X': 4, 'N': 3, 'Y': -1}[c] for c in s]` will convert the strings to the needed input format.

You can Try it online! (Thanks to Jonathan Frech for the suggestion)
> 2 votes

# Answer
# Python 3, ~~187~~ 156 bytes

Really not that competitive with the other python answers on this, but I had some good ideas for using dicts to make an answer that actually takes string inputs, and it didn't turn out horribly long.

```
def E(s):
 r,g,*v=range(len(s)),lambda**d:d.get(s[i],0),*s
 for i in r:v[i]=g(A=1,B=-1)
 for i in r:v[i]=g(X=1,Y=-1)*v[(i-1,i+1)[i<1]]or v[i]
 return sum(v)

```

Try it online!

Edit -21 bytes: Some beautifully horrific abuse of python by @Unrelated String

Loops through the input twice to fill out an output list containing the vote of each person (`1` for `A`, `-1` for `B`, `0` for no vote), and filling out the `X`s and `Y`s on the second loop. I thought I could do it with one loop, but irritatingly that fails on an `X` or `Y` at the beginning of the string, as it hasn't processed the following vote yet. The return value is positive if candidate 1 wins, and negative if candidate 2 wins. (The absolute value of it also happens to be the margin of victory)
> 2 votes

# Answer
# Perl 5, 54 bytes

```
s/^\W(?=(\w))|(\w)\K\W/$1^$2^$&/e&&redo;$_=y/A//>y/B//

```

Try it online!

Uses `A` for `A`, `B` for `B`, `N` for `N`, `\0` for `X` and `\3` for Y (the last two being literal control chars). The trick is that `A` bitwise-xor `\3` equals `B`, and vice-versa.
> 1 votes

# Answer
# Javascript (ES6) - 133 bytes

```
a=>(i=($=_=>'AB'.search(_)+1)(a[1],o=0),[...a].map(v=>(r=['NAB','NBA']['XY'.search(x)],p=r?r[i]:v,i=$(p),o+='NA'.search(p))),o>0?1:2)

```

Takes in a string with the format given in the OP and returns *1* if candidate 1 won and *2* otherwise (I'll admit it, I'm even-biased).
> 1 votes

---
Tags: code-golf, string, decision-problem
---


title: Fourth Time's the Triple Tap

text:
# Question
Title: Fourth Time's the Triple Tap
The sci-fi shooter Destiny 2 contains guns which have the ability to regenerate ammunition directly into the magazine **if, and only if** `x` (precision) shots are landed (in a fixed amount of time), returning `y` bullets to the magazine. For example, the perk (ability) "Triple Tap" will return 1 bullet to the magazine if 3 precision hits are landed (`x = 3, y = 1` in this case). A gun may also have multiple perks.

**Task**
Your task is to take the initial magazine capacity of a gun, and take a list of perks in the form of `x` and `y`s in a suitable format, and return the highest number of shots that could be fired before having to reload the weapon. Input may be in any form suitable (list with magazine capacity as element 0, list of tuples, list/capacity being two different variables etc.)

**Examples**

```
Input1 = [4, (3, 1)] # format here is [magazine, (x, y)...]
Output1 = 5

Input2 = [6, (3, 1), (4, 2)]
Output2 = 23

Input3 = [100, (1, 2)]
Output3 = NaN # any version of NaN or Infinity would be fine here

```

A worked example of Input2/Output2 can be found here (courtesy of @Arnauld in comments).

**Rules**

* All values (including magazine size) maybe be zero, but never negative.
* Input/Output may be in any suitable form.

This is , so shortest answer wins!

# Answer
# , 60 51 bytes

```
(0(i.~+_*1-e.)[+/\@,(*#)$])_1++/@(*0=]|/1+[:i.*./)/

```

Try it online!

Feels like there might be a closed form solution, but I didn't find one. So instead I simulate the required number of times, which is bounded (see explanation).

Consider `6 f (1 2,:3 4)` where we take the perks as the right argument, as a matrix like this:

```
1 2 <- y values
3 4 <- x values

```
* `1+[:i.*./)/` 1...\<the LCM of 3,4\>:

```
1 2 3 4 5 6 7 8 9 10 11 12

```
* `]|/` Modded by 3 and 4:

```
1 2 0 1 2 0 1 2 0 1 2 0
1 2 3 0 1 2 3 0 1 2 3 0

```
* `0=` Where does that equal 0:

```
0 0 1 0 0 1 0 0 1 0 0 1
0 0 0 1 0 0 0 1 0 0 0 1

```
* `*` Multiply elementwise by `1 2`:

```
0 0 1 0 0 1 0 0 1 0 0 1
0 0 0 2 0 0 0 2 0 0 0 2

```
* `+/@` Sum the rows:

```
0 0 1 2 0 1 0 2 1 0 0 3

```
* `_1+` Minus 1:

```
_1 _1 0 1 _1 0 _1 1 0 _1 _1 2

```
* `((*#)$])` Repeat that 6 times:

```
_1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2 _1 _1 0 1 _1 0 _1 1 0 _1 _1 2

```
* `[+/\@,` Append the 6 and scan sum:

```
6 5 4 4 5 4 4 3 4 4 3 2 4 3 2 2 3 2 2 1 2 2 1 0 2 1 0 0 1 0 0 _1 0 0 _1 _2 0 _1 _2 _2 _1 _2 _2 _3 _2 _2 _3 _4 _2 _3 _4 _4 _3 _4 _4 _5 _4 _4 _5 _6 _4 _5 _6 _6 _5 _ 6 _6 _7 _6 _6 _7 _8 _6

```

+ The answer is now the index of the first 0. If there is no zero within 6 repetitions, there there will never be a 0, and we can continue forever.
* `0(i.~+_*1-e.)` Find the index of the first 0, and add infinity if there is no zero:

```
23

```
> 8 votes

# Answer
# 05AB1E, 25 bytes

```
˜>P*U¹εÅ0`gª¦Xи}.«+<.¥+0k

```

First input as a list of `[x,y]` pairs, second input the starting ammunition.
Outputs `-1` for `Infinity`/`NaN`, because 05AB1E doesn't have either.

Port of *@Jonah*'s J answer.
Thanks to *@DominicVanEssen* for noticing some bugs in my program (previously failed if \\$y\>x\\$; if there were a mixture of both valid and invalid \\$\[x,y\]\\$ pairs in the input; and if either \\$x=0\\$ and/or \\$y=0\\$).

Try it online or verify all test cases.

**Explanation:**

```
˜           # Flatten the (implicit) first input-list of [x,y]-pairs
 >          # Increase each by 1 (edge case for the 0s)
  P         # Take the product of this list
   *        # Multiply it by the (implicit) second input-integer
    U       # Pop and store this value in variable `X`
¹ε          # Map over the [x,y]-pairs of the first input-list:
  Å0        #  Convert both to a list of that many 0s
    `       #  Pop and push both lists of 0s to the stack
     g      #  Pop the top and get its length to transform it back into an integer
      ª     #  Append it to the list
       ¦    #  Remove the first 0
            #  (an [x,y] pair is now a list of x-1 amount of 0s appended with y)
        Xи  #  Cycle-repeat this list `X` amount of times
 }          # After the map:
  .«        # Reduce the list of infinite lists by:
    +       #  Adding the values at the same positions together
     <      # Then decrease each by 1
      .¥    # Undelta this list with leading 0
        +   # Add the second (implicit) input-integer to each value
         0k # Get the 0-based index of the fist 0 (or -1 if there are none)
            # (after which the top of the stack is output implicitly as result)

```
> 4 votes

# Answer
# Charcoal, 26 bytes

```
Ｉ⌕Ｅ×θΠＥη§ι⁰⁻ιΣＥη×÷ι§λ⁰§λ¹θ

```

Try it online! Link is to verbose version of code. Takes the capacity and list of perks as separate inputs. Charcoal doesn't have `Infinity` or `NaN` so `-1` is output instead. Explanation:

```
 ⌕                          Find index of
                         θ  Capacity in
      Ｅη                    Map over perks
        §ι⁰                 Perk `x` value
     Π                      Take the product
   ×                        Multiplied by
    θ                       First input
  Ｅ                         Map over implicit range
            ι               Current value
           ⁻                Subtract
              Ｅη            Map over perks
                  ι         Current value
                 ÷          Integer divided by
                   §λ⁰      Perk `x` value
                ×           Multiplied by
                      §λ¹   Perk `y` value
             Σ              Take the sum
Ｉ                           Cast to string
                            Implicitly print

```
> 3 votes

# Answer
# JavaScript (ES6), 67 bytes

Expects `(magazine)(perks)`. Returns `NaN` for ∞.

This processes a simulation, one shot at a time.

```
(n,q=0,m=n)=>g=a=>m?n>m--|!q++?g(a,a.map(([x,y])=>q%x?0:m+=y)):+g:q

```

Try it online!

### Commented

```
( n,                    // n = initial number of bullets
  q = 0,                // q = number of shots
  m = n                 // m = number of bullets in the magazine
) =>                    //
g = a =>                // a[] = array of perks, in [x, y] format
m ?                     // if there's still at least one bullet:
  n > m-- |             //   if m is less than n (decrement m afterwards)
  !q++ ?                //   or q is still 0 (increment q afterwards):
    g(                  //     do a recursive call:
      a,                //       pass a[] unchanged
      a.map(([x, y]) => //       for each perk [x, y] in a[]:
        q % x ?         //         if x does not divide q:
          0             //           do nothing
        :               //         else:
          m += y        //           add y bullets
      )                 //       end of map()
    )                   //     end of recursive call
  :                     //   else:
    +g                  //     return NaN
:                       // else:
  q                     //   return the total number of shots

```
> 3 votes

# Answer
# Clojure, 160 bytes

```
#(loop[m %[x & y](apply map vector(for[[a b]%&](cycle(concat(repeat(dec a)0)[b]))))i 0](cond(= 0 m)i(>=(- m)%)(/ 1 0.)1(recur(apply - 1(Math/abs m)x)y(inc i))))

```

Try it online!

Similarly to Jonah's answer, this simulates the shooting process. However, as Clojure's collections are lazy, we do not set any bounds, but cycle through infinite lists of extra added bullets (like `0 0 1 0 0 1 0 0 1...`) until the number of bullets in the magazine `m` reaches zero.

When at any stage the magazine is refilled to its maximum capacity, this should go on indefinitely, and in such case Infinity is returned. Note: Clojure version on TIO is probably too old, as it doesn't accept `##Inf` literal.
> 2 votes

# Answer
# , ~~78~~ 75 bytes

```
function(a,x,y){b=a;while(sum(x*a)&(a=a+sum(y[!T%%x])-1)<b)T=T+1;T/(a<b)-1}

```

Try it online!

Input is ammunition `a`, a vector of `x` hit values, and a vector of the corresponding `y` perk values.
Uses either `Inf` or `NA` as "any version of NaN or Infinity" output options...
> 1 votes

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


title: Make a +-= Interpreter

text:
# Question
Title: Make a +-= Interpreter
+-= is a language created by Esolangs user Anonymous in 2017.
The language consists of only three commands:

* `+` increases the accumulator by one.
* `-` decreases the accumulator by one.
* `=` outputs the accumulator and a newline.

## Rules

* This is , all usual golfing rules apply.
* Standard rules apply.
* You may assume input will be valid.
* Interpreters must get input once and output the result.

## Test cases

```
+++++=
5

+=+=+=+=+=+=+=+=+=+=
1
2
3
4
5
6
7
8
9
10

+++==
3
3

+-=
0

=
0

-=
-1

---=++-=
-3
-2

```

# Answer
# Charcoal, 16 bytes

```
ＩＥ⌕Ａθ=⁻ι⁺κ⊗№…θι-

```

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

```
    θ               Input string
  ⌕Ａ                Find all indices of
     =              Literal string `=`
 Ｅ                  Map over indices
       ι            Current index
      ⁻             Subtract
         κ          Number of previous `=`
        ⁺           Plus
           №…θι-    Number of previous `-`
          ⊗         Doubled
Ｉ                   Cast to string
                    Implicitly print

```

The number any given `=` prints is equal to the number of `+`s so far minus the number of `-`s so far. The number of `+`s so far plus the number of `-`s so far plus the number of `=`s so far is of course the index of the `=` in question, so the number of `+`s plus `-`s can be calculated from the difference, and the difference between the number of `+`s and `-`s by further subtracting double the number of `-`s.

As @Jonah points out in his J answer, you can also translate the `-=+` characters to the integers `-1..1`, and output the cumulative sums at the positions of the `0`s. This also takes 16 bytes in Charcoal:

```
ＩＥ⌕Ａθ=ΣＥ…θ⊕ι⌕=+λ

```

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

```
    θ               Input string
  ⌕Ａ                Find all indices of
     =              Literal string `=`
 Ｅ                  Map over indices
         θ          Input string
        …           Truncated to length
           ι        Current index
          ⊕         Incremented
       Ｅ            Map over characters
               λ    Current character
            ⌕       Find index in
             =+     Literal string `=+`
      Σ             Take the sum
Ｉ                   Cast to string
                    Implicitly print

```

Charcoal's `Find` returns `-1` when there is no match, which is what we want for `-`.
> 3 votes

# Answer
# , 29 26 25 bytes

```
0(=echo"++/\@])'-='&i.-1:

```

Try it online!

*-3 thanks to ovs!*

*-1 thanks to Neil!*

Inspired by Neil's answer.

Consider `+=+=`:

* `'-='&i.-1:` Convert `-=+` to `_1 0 1`

```
1 0 1 0

```
* `0(=...+/\@])` Scan sum and filter only elements at the `0` positions:

```
1 0 1 0  ...  1 1 2 2
1 2                  NB. 1 and 2 are the values at the 0 positions

```
* `echo"+` Print each value

```
1
2

```
> 2 votes

# Answer
# C (gcc), 73 bytes

```
f(char*p){int a=0;p--;while(*++p)*p==43?a++:*p==45?a--:printf("%d\n",a);}

```

Ungolfed:

```
void f(char*p){
    int a=0; // Accumulator
    p--; // The loop increases the pointer so compensate
    while(*++p){
        if(*p==43)a++; // 43 and 45 are ASCII codes for + and -
        else if(*p==45)a--;
        else printf("%d\n",a);
    }
}

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 44 bytes

```
=
=¶$`=
-1=A`
%O`.
+`\+-

((-)+|\+*)=+
$2$.1

```

Try it online! Link includes test cases. Explanation:

```
=
=¶$`=

```

Prepend all of the prefixes of the input that end in an `=`.

```
-1=A`

```

Delete the original input. (Assuming it ended in an `=`, this will have been prepended as the last prefix.)

```
%O`.

```

Sort the characters in each prefix.

```
+`\+-

```

Cancel out the `+`s with the `-`s.

```
((-)+|\+*)=+
$2$.1

```

Convert to decimal.
> 1 votes

# Answer
# 05AB1E, 10 bytes

```
Î„+-„><‡.V

```

Try it online or verify all test cases.

**Explanation:**

```
Î           # Push 0 and the input
 „+-        # Push string "+-"
    „><     # Push string "><"
       ‡    # Transliterate all "+" to ">" and "-" to "<" in the input
        .V  # Evaluate and execute as 05AB1E code:
            #  `>`: Increase the top by 1
            #  `<`: Decrease the top by 1
            #  `=`: Print the top with trailing newline, without popping

```

Because `=` in 05AB1E does exactly what we want it to in +-=, it might be the perfect language for this challenge.
> 0 votes

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