title: 2D Pathfinding with Momentum

text:
# Question
Title: 2D Pathfinding with Momentum
You are piloting a spaceship, outfitted with an engine that can accelerate you at 1km/s^2 in the direction the ship is facing (you have very good inertial dampers). You also have thrusters which can rotate you 180 degrees in 1s (rotating 45 degrees takes 0.25s, etc.).

You see on your scanner another ship, and decide to rendezvous with it. You'll need to plot a course which brings you within 1km of it while your speed is within 1km/s of its speed.

## Specifications

Write a function which takes the following pieces of data as inputs:

`other_location` \- The location of the other ship in kms. You may assume that this is no more than 100 units away from the origin for optimization, but your entry should be able to handle larger distances (even if it takes a long time).

`other_acceleration` \- The other ship is accelerating at a constant rate no more than 0.5km/s^2 (their inertial dampers aren't quite as good). You may take this in whatever form you wish - facing + acceleration, or separated into x and y components). The other ship starts at a speed of 0.

You always start at `[0,0]`, facing the positive direction on the x axis.

Your function's output is significantly more constrained. You must return a list of actions your ship will take. There are three possible actions.

1. Acceleration. You accelerate in the direction your ship is facing for an amount of time you specify.
2. Rotation. You rotate to face a direction you specify.
3. Drift. You do nothing for the amount of time you specify.

Your output must have the listed data, but it can be in any format you wish. Please make it human-readable; this isn't code golf.

At the end of the final action in your list, your ship must be within 1km of the other ship and its speed must be within 1km/s of the other ship's speed. Note that if you accelerate from a stop for 1s, you will have moved 0.5kms.

## Scoring Criteria

I will run each entry on my machine, a i7-9750H 2.6 GHz Windows 10 laptop. Ideally, there will be straightforward installation instructions for your language; please specify whatever build command I need to run it.

The score of an entry on a particular input will be the product of the time it takes to run and the time that it takes for your ship to intercept the other ship squared. Entries may be non-deterministic, but I will run any non-deterministic entry 10 times on each input and take the worst score.

The winner will be the entry that has the lowest total score across the inputs.

## Example inputs

Here are a bunch of sample inputs (that I'll use as the test set, though I might add some more if some programs are very quick). Feel free to post preliminary outputs/scores for each of these (run on your machine), but note that it's a standard loophole to tailor your program to these inputs.

```
other_location (x, y), other_acceleration (x, y)
[10,0], [0,0]
[6,-3], [0,0.5]
[-2,8], [0.1,-0.2]
[5,5], [0.3,0.3]
[15,18], [0.1, 0.3]
[20,5], [0.2,-0.2]

```

## Example output

For the first example input (`[10,0], [0,0]`), these are all valid outputs:

```
[Accelerate, 1], [Drift, 8.5]
[Accelerate, 2.7], [Rotate, 180], [Accelerate, 2.7]
[Accelerate, 2], [Rotate, [-1,0]], [Drift, 2], [Accelerate, 2]

```

For the second example input (`[6,-3], [0,0.5]`), this is a valid output:

```
[Accelerate, 2.23], [Rotate, 180], [Accelerate, 2.23], [Rotate, -90],
[Accelerate, 11.5], [Drift, 5.5]
// The first 3 actions put me directly behind the moving ship (actually
// at [5.9729, 0]) in 5.96s (the other ship is now at [6,5.8804] and
// moving [0, 2.98]), the remainder catch up to it.
// Total time for this route: 22.96s

```

# Answer
# MATLAB

Try it online

```
function tf=Intercept(p,a)
X=@(t,a,v,x).5*a*t.^2+v.*t+x;
t=0;
while 1

    a1=(0:0.01:1)';
    a2=1-a1;
    theta2=-360:360;

    x1=X(t,a(1),0,p(1));
    y1=X(t,a(2),0,p(2));
    theta1=atan(y1/x1)*180/pi;
    T=(t-abs(theta1)/180-abs(theta2-theta1)./180);
    T(T<0)=0;
    x2=0.5*a1.^2*cosd(theta1).*T.^2+0.5*a2.^2*cosd(theta2).*T.^2+a1.*a2*cosd(theta1).*T.^2+a1.*cosd(theta1)*T.*abs(theta2-theta1)/180;
    y2=0.5*a1.^2*sind(theta1).*T.^2+0.5*a2.^2*sind(theta2).*T.^2+a1.*a2*sind(theta1).*T.^2+a1.*sind(theta1)*T.*abs(theta2-theta1)/180;
    x=x1-x2;
    y=y1-y2;
    vx=a(1)*t-(a1*cosd(theta1)*T+a2*cosd(theta2).*T);
    vy=a(2)*t-(a1*sind(theta1)*T+a2*sind(theta2).*T);
    V=sqrt(vx.^2+vy.^2);
    D=sqrt(x.^2+y.^2);

    [ida1,idtheta2]=find(D<1&V<1,1);

    if ~isempty(idtheta2)
        a1=a1(ida1);
        theta2=theta2(idtheta2);
        break
    end

    t=t+0.01;

end
if length(theta2) > 1
    return
end
tf=t;
t1=abs(theta1/180);
t3=abs(theta2-theta1)/180;
t3=t3-0*(t3>1);
t2=a1.*(tf-t1-t3);
t4=tf-t3-t2-t1;
x1=a(1)/2*tf^2+p(1);
y1=a(2)/2*tf^2+p(2);
v1=a*tf;
x2=cosd(theta1)/2.*t2.^2+cosd(theta1).*t2.*(t3+t4)+cosd(theta2)./2.*t4.^2;
y2=sind(theta1)/2.*t2.^2+sind(theta1).*t2.*(t3+t4)+sind(theta2)./2.*t4.^2;
v2=[cosd(theta1)*t2+cosd(theta2)*t4;sind(theta1)*t2+sind(theta2)*t4];
V=vecnorm(v1'-v2);
P=vecnorm([x1;y1]-[x2;y2]);
cmds=[theta1,t1,t2,theta2-theta1,t3,t4,tf];
fprintf('Turn %.2f degrees in %.2f seconds\nAccelerate for %.2f seconds\nTurn %.2f degrees in %.2f seconds\nAccelerate for %.2f seconds\nMission Time: %.2f seconds\n\n',cmds);
fprintf('x1=%.2f, x2=%.2f\ny1=%.2f, y2=%.2f\nv1=[%.2f %.2f], v2=[%.2f %.2f]\nV=%.2f\nD=%.2f\n',x1,x2,y1,y2,v1,v2,V,P);

```

Explanation:

My methodology is to start by assuming the total mission length \\$t\\$ starting from 0 (in the case where we already fit the parameters at \\$t\\$=0) and apply a standard mission profile. The mission has 4 stages:

1. turn towards where the target will be at time \\$t\\$
2. accelerate towards the target
3. turn to an angle that will cancel velocities so that we are within parameters by time \\$t\\$
4. accelerate for the remaining time

Using this profile, there are 4 time values to be concerned about. \\$t\_1\\$ is the first turn, \\$t\_2\\$ is the first burn, \\$t\_3\\$ is the second turn, and \\$t\_4\\$ is the last burn. \\$t\_1\\$ is known since the initial angle can be easily calculated. \\$t\_2\\$ and \\$t\_4\\$ are calculated as percentages \\$a\_1\\$ and \\$a\_2\\$ of \\$(t\_2+t\_4)\\$, in order to reduce them to \\$a\_1(t\_2+t\_4)\\$ and \\$(1-a\_1)(t\_2+t\_4)\\$, thus making both values a function of \\$a\_1\\$. \\$t\_3\\$ is a function of the second turn angle \\$\theta\_2\\$. The next thing is to calculate the x and y positions and velocities at time \\$t\\$ as a function of \\$a\_1\\$ and the second angle \\$\theta\_2\\$, the only other unknown. I know that these are limited to a specific range of 0:1 and -360:360 respectively, so I calculate all possible positions as a function of \\$a\_1\\$ and \\$\theta\_2\\$ and find the first one that fits the criteria. If none fit, then \\$t\\$ is increased by 0.01 and the process is repeated. This method takes advantage of the vectorized computing capabilities of MATLAB. And honestly, it's probably the first code golf challenge where MATLAB is more ideal.

I also have some test code that has all of the test cases already, and times it as well according to your scoring criteria. Since the output of the program is the total mission time, and tic/toc calculates time since tic was called at time toc, this calculates the score as well.

% % Test Intercept\*

\*edited so that toc comes after the function call, so that time is calculated after the function finishes and not before. Oversight on my part.

```
tic
(Intercept([10,0], [0,0])*toc)^2;

tic
(Intercept([6,-3], [0,0.5])*toc)^2

tic
(Intercept([-2,8], [0.1,-0.2])*toc)^2

tic
(Intercept([5,5], [0.3,0.3])*toc)^2

tic
(Intercept([15,18], [0.1, 0.3])*toc)^2

tic
(Intercept([20,5], [0.2,-0.2])*toc)^2

```
> 3 votes

---
Tags: code-challenge, fastest-code, path-finding
---


title: Two Diehards Make a Glider

text:
# Question
Title: Two Diehards Make a Glider
In Conway's Game of Life, there is an infinite square grid of cells, each of which is alive or dead. The pattern changes each "generation". A dead cell with exactly 3 live neighbors (orthogonal or diagonal) becomes a live cell. A live cell only lives to the next generation if it has 2 or 3 live neighbors. These simple rules lead to very complex behaviors. The most well-known pattern is the glider, a pattern that moves diagonally one cell every 4 generations and looks like this:

## The Challenge

Your task is to create two patterns which will eventually result in an empty board when by themselves (a.k.a. a diehard), but when combined in a certain non-bordering and non-overlapping arrangement, eventually spawn a single glider and nothing else.

## Rules and Scoring

* Each of the lone diehards must fit all live cells within a 100x100 cell box and may not contain more than 100 live cells.
* The combination glider synthesizer must contain both diehards such that their bounding boxes surrounding all live cells are separated by at least one dead cell.
* It does not matter which direction the single glider is facing
* Your score is the sum of the number of generations it takes to reach an empty board from the initial states for the diehards, plus the number of generations it takes to reach a state where there is exactly one glider and nothing else (i.e. there are *exactly* 5 live cells on the board in a glider pattern) for the combined glider synthesizer. **Highest score wins**.

# Answer
> 5 votes
# Total Score ~~669~~ ~~683~~ 753

**Pattern 1 (379 steps)**:

```
x = 100, y = 94
97b2o$96bo2bo$97bobo$98bo$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$3o$2bo$bo!

```

**Pattern 2 (126 steps)**:

```
x = 11, y = 2
o5b2obo$3bo$2b2o2bo2b2o!

```

**Pattern 1 + Pattern 2 (248 steps)**:

```
x = 112, y = 94
97b2o$96bo2bo$97bobo$98bo2bo5b2obo$104bo$103b2o2bo2b2o$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$3o$2bo$bo!

```

Pattern 1 is a self-destructing glider + loaf combination where the glider and loaf are spaced as far apart as possible.

Pattern 2 is the result of searching for random disappearing patterns which can be placed next to pattern 1 to destroy the loaf, giving a valid solution to the puzzle. I generated a large number and took the one with the best score.

I'm sure its possible to do better by adding an independent diehard to the far corner of pattern 2 (or even pattern 1), but I'm done for now.

---
Tags: code-challenge, source-layout, game-of-life
---


# Question
Title: Shortest code to find next prime palindrome
I was trying to find the shortest code possible that given a number n, returns the next prime palindrome number (limited to below 100000). If the number itself is a prime palindrome, the code should return the next one.

Write the shortest program/function that, when given an input `n` (less than `100000`), returns the next palindromic prime number.

This is an example working program:

```
def golf(n):
    n+=1
    while str(n)!=str(n)[::-1] or not all(n%i for i in xrange(2,n)):n+=1
    return n

```

# Answer
# CJam, 15 bytes

```
li{)__mfsW%i^}g

```

Reads a single, positive integer from STDIN. Try it online.

### Example run

```
$ cjam <(echo 'li{)__mfsW%i^}g') <<< 250
313

```

### How it works

This uses a tricky prime check instead of the built-in `mp`:

`15 mf`, for example, pushes `[3 5]`. We cast to a string (`"35"`), reverse that string (`"53"`), cast to integer (`53`) and XOR the result with the original integer (`22`). Since the result in non-zero, `35` is not a palindromic prime.

```
li                 " N := int(input())        ";
  {          }g    " While R:                 ";
   )               "   N += 1                 ";
     _mfs          "   R := str(factorize(N)) ";
         W%i       "   R := int(reverse(K))   ";
    _       ^      "   R ^= N                 ";

```
> 6 votes

# Answer
# Brachylog, 4 bytes

```
<.ṗ↔

```

Try it online!

Simple and neat.

```
?<.ṗ↔.     (Initial ? and final . are implicit)
?<.        Input is less than the output
  .ṗ       Output is a prime number
    ↔.     And output reversed is the output itself (it is a palindrome)

```
> 5 votes

# Answer
## CJam, ~~18~~ 17 characters

```
ri{)__s_W%=*mp!}g

```

How it works:

```
ri                     "Convert the input into an integer";
  {            }g      "Run this code block while the top stack element is truthy";
   )__                 "Increment the number and make two copies";
      s_               "Convert one of them to string and take another copy";
        W%=            "Reverse the last string and compare with second last";
           *           "If they do not match, make the second last number 0";
            mp!        "Put 1 to stack if number is not prime, continuing the loop";

```

Try it online here
> 4 votes

# Answer
## Python, ~~63~~ 60 characters

```
def g(n):
 n+=1
 while`n`[::-1]!=`n`or~-2**n%n>2:n+=1
 return n

```
> 4 votes

# Answer
### Mathematica - 75 characters

```
i=IntegerDigits;f@n_:=Select[Range[n+1,10^5],i@#==Reverse@i@#&&PrimeQ@#&,1]

```

Ungolfed:

```
i=IntegerDigits;
f@n_:=Select[
  Range[n+1,10^5],
  i@#==Reverse@i@#
  &&
  PrimeQ@#
  &,
  1
]

```

Sets an alias for the IntegerDigits function, then defines a function which selects the first number on the list of n+1 to 100,000 which satisfies PrimeQ and has palindromic digits. The function is called `f@50000`, returning `{70207}`.
> 2 votes

# Answer
## Haskell - 71

```
p n|s==reverse s&&all((/=0).mod m)[2..n]=m|1<2=p m where m=n+1;s=show m

```

Ungolfed

```
nextPrime n
  | s == reverse s && all ((/=0).(mod m)) [2..n] = m
  | otherwise = nextPrime (n + 1)
  where
    m = n + 1
    s = show m

```
> 1 votes

# Answer
# Pyth, 17

```
~Q1Wn`Q_`ePQ~Q1)Q

```

Explanation:

```
                         Implicit: Q = eval(input())
~Q1                      Q +=1
W                        while
 n                       not equal
  `Q                     repr(Q)
    `ePQ                 repr(end(prime_factorization(Q)))
 ~Q1                     Q += 1
)                        end while
Q                        print(Q)

```
> 1 votes

# Answer
# Ruby, 63

```
require"prime"
x=->n{Prime.find{|p|q=p.to_s;p>n&&q.reverse==q}}

```

## Explanation

* Input is taken as the arguments to a lambda. It's expected to be an `Integer`.
* `Prime` is `Enumerable`. Use `Enumerable#find` to find the first prime that's bigger than the input and is equal to itself when reversed.
> 1 votes

# Answer
# K (oK), 27 bytes

```
{~(x=.|$x)&/(2_!x)!'x}(1+)/

```

Try it online! for all test cases where the input `n<1000`

My first answer in K. Yay!

Thanks to @ngn for the help.

ngn also found a shorter solution which is very wasteful. Times out on TIO for `n>919`.

```
{x+(~x=.|$x)|/x=*/!2#x}/

```

### How?

```
{~(x=.|$x)&/(2_!x)!'x}(1+)/    # Main function f, argument x
 ~                             # Not
  (x=.|$x)                     # x equals the inverse of x (is a palindrome)
          &/                   # And reduction; will return truthy iff all
                               # results in the list are truthy (not 0)
            (2_!x)             # range [2..x]
                  !'x          # each modulo x
{                    }(1+)/    # While loop with x+1; returns x implicitly.

```
> 1 votes

# Answer
# Japt, 11 bytes

```
_¥sÔ©Zj}aUÄ

```

Run it online
> 1 votes

# Answer
# JavaScript (E6) 95

```
Q=n=>(f=>{for(;a=!f;)for(f=++n==[...n+''].reverse().join('');b=n/++a|0,f&&a<=b;)f=a*b-n;})(0)|n

```

**Ungolfed**

```
Q=n=>
{
  for (f=0; !f;) // loop until both palindrome and prime
  {
    f = ++n == [...n+''].reverse().join(''); // palindrome check
    if (f) // if palindrome, check if prime
      for(a = 1; b=n/++a|0, f && a<=b; )
        f = a*b-n;
  }
  return n
}

```

**Test** In FireBFox/FireBug console

```
for (o=[],i=9;i<100000;)o.push(i=Q(i));console.log(o)

```

*Output*

```
[11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551, 16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991, 30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543, 34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183, 38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237, 73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787, 78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349, 94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389, 98689, 1003001]

```
> 0 votes

# Answer
# 05AB1E (legacy), 9 bytes

```
[>ÐÂQsp*#

```

Try it online or verify some test cases.

**Explanation:**

```
             # (Implicit input)
             #  i.e. 15
             #  i.e. 130
[            # Start an infinite loop
 >           #  Increase the top of the stack by 1
             #   i.e. 15 + 1 → 16
             #   i.e. 100 + 1 → 101
  Ð          #  Triplicate that value
   Â         #  Bifurcate it (short for Duplicate & Reverse)
             #   i.e. 16 → 16 and '61'
             #   i.e. 101 → 101 and '101'
    Q        #  Check if it's equal (this checks if the number is a palindrome)
             #   i.e. 16 and '61' → 0 (falsey)
             #   i.e. 101 and '101' → 1 (truthy)
     s       #  Swap so the value is at the top of the stack again
      p      #  Check if it's a prime
             #   i.e. 16 → 0 (falsey)
             #   i.e. 101 → 1 (truthy)
       *     #  If it's both a palindrome and a prime:
             #    i.e. 0 and 0 → 0 (falsey)
             #    i.e. 1 and 1 → 1 (truthy)
        #    #   Stop the infinite loop
             # (Implicitly outputs the resulting value)

```
> 0 votes

# Answer
# 05AB1E, 7 bytes

```
[ÅNDÂQ#

```

Try it online!

```
[ÅNDÂQ#  # full program
      #  # exit...
[        # infinite loop...
      #  # when...
 ÅN      # first prime greater than...
         # implicit input...
   D     # or top of stack if not first iteration...
    ÂQ   # is equal to...
 ÅN      # first prime greater than...
         # implicit input...
   D     # or top of stack if not first iteration...
    Â    # reversed
         # (implicit) exit infinite loop
   D     # implicit output

```
> 0 votes

# Answer
# Raku, 37 bytes

```
{first &is-prime&{.flip eq$_},$_^..*}

```

Try it online!

The outer expression is `first EXPR, $_ ^.. *`, which looks for the first number which matches `EXPR` in the numbers from one greater than the input argument `$_` to infinity. (The caret `^` in front of the `..` means to exclude the starting point from the range.)

`EXPR` is an and-junction of two function, the built-in `&is-prime` and the anonymous function `{ .flip eq $_ }`, which tests for palidrome-ness. A number matches this junction only if it matches both members.
> 0 votes

---
Tags: code-golf, primes, palindrome
---


title: Placing circles along a square spiral

text:
# Question
Title: Placing circles along a square spiral
In this code golf challenge, you'll be computing the placement of (open) circles of areas \\$\pi, 2\pi, 3\pi, \dots\\$ when greedily placed along integer points in a square spiral in such a way that no two overlap.

A square spiral is a sequence in \\$\mathbb Z^2\\$ that starts at \\$(0,0)\\$ and successively wraps around the origin. (Like Arnauld, you might find inspiration from this CGSE question.)

```
(0, 0) -> (1, 0) -> (1, 1) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (-1, -1) -> (0, -1) -> (1, -1) -> (2, -1) -> (2, 0) -> (2, 1) -> (2, 2) -> (1, 2) -> (0, 2) -> (-1, 2) -> (-2, 2) -> (-2, 1) -> (-2, 0) -> (-2, -1) -> (-2, -2) -> (-1, -2) -> (0, -2) -> (1, -2) -> (2, -2) -> (3, -2) -> (3, -1) -> (3, 0) -> (3, 1) -> (3, 2) -> ...

```

---

In this challenge, you will start at the origin, walk around the spiral, and place circles with areas \\$\pi, 2\pi, 3\pi\\$, at integer points in a greedy fashion, as shown in the GIF below.

The first seven circles are:

* a circle of area \\$\pi\\$ placed at \\$(0,0)\\$,
* a circle of area \\$2\pi\\$ placed at \\$(2,2)\\$,
* a circle of area \\$3\pi\\$ placed at \\$(-2,2)\\$,
* a circle of area \\$4\pi\\$ placed at \\$(3,-2)\\$,
* a circle of area \\$5\pi\\$ placed at \\$(-3,-3)\\$,
* a circle of area \\$6\pi\\$ placed at \\$(5,5)\\$, and
* a circle of area \\$7\pi\\$ placed at \\$(0,6)\\$.

Again, the circles are placed as soon as they fit. The second circle could not be placed at \\$(1,0)\\$, \\$(1,1)\\$, \\$(0,1)\\$, \\$(-1,1)\\$, \\$(-1,0)\\$, \\$(-1, -1)\\$, \\$(0,-1)\\$, \\$(1, -1)\\$, \\$(2, -1)\\$, \\$(2, 0)\\$, or \\$(2, 1)\\$ without overlapping with the first circle, but it could be—and is—placed at \\$(2,2)\\$.

Once we've placed "all" of the blue circles, we start over. In the second generation, we place "red" circles with areas \\$\pi, 2\pi, 3\pi\\$, in a greedy fashion:

Once we've placed all of the red circles from the second generation, we move onto yellow circles, cyan circles, magenta, dark green, purple, light green, orange, brown circles, and so on.

# Challenge

Okay! That's a lot of setup! Here's your challenge:

Write a program that takes in two positive (alternatively, \\$0\\$-indexed) integers, `g` and `k`, and outputs the position of the circle of area \\$k\pi\\$ in the \\$g\\$-th generation.

When \\$g=1\\$, this corresponds to the blue circles; when \\$g=2\\$, this corresponds to the red circles; when \\$g=3\\$, the yellow circles, and so on.

Your program should be able to compute all of the values in the following table in practice, and it should be able to compute bigger values (without running into floating point errors) in principle.

### Data table

```
 g |  k | position   | (color in GIFs; for reference only)
---+----+------------+------------------------------------
 1 |  1 | (0, 0)     | blue
 1 |  2 | (2, 2)     | blue
 1 |  3 | (-2, 2)    | blue
 1 | 50 | (36, -18)  | blue
 2 |  1 | (0, -4)    | red
 2 |  2 | (-3, 9)    | red
 2 | 14 | (-2, -59)  | red
 2 | 15 | (-66, 28)  | red
 3 |  1 | (-5, 2)    | yellow
 3 |  2 | (4, -10)   | yellow
 3 | 10 | (-58, 3)   | yellow
 8 |  1 | (-6, 10)   | orange
 8 |  2 | (16, 21)   | orange
 8 |  3 | (-27, -19) | orange
 9 |  1 | (-10, 6)   | crimson
 9 |  2 | (-25, 4)   | crimson
 9 |  3 | (17, -27)  | crimson

```

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

```
g=>k=>{for(N=1;n=N;N*=2)for(G=g,C=[];G--;n-=r*3)for(o=[x=X=0,Y=y=s=1];x<n;o[[x+Y,y+X]]?0:[X,Y]=[Y,-X])if(!(o[[x+=X,y-=Y]]=C.some(([X,Y,R])=>Math.hypot(X-x,Y-y)<R+r,r=s**.5)||s++-k|G*C.push([x,y,r])))return[x,y]}

```

Try it online!

---

```
g=>  // input: generation
k=>{ // input: circle area
for(
 N=1; // Search bound, we try to search generation 1
      // circles in [-N,N]x[-N,N]
 n=N; // Search bound of current generation
 N*=2 // If we cannot locate (g,k) circle
      // we try a larger bound later
)
 for(
  G=g, // Number of generation (count down)
  C=[]; // All Circles found yet
  G--; // Count down 1 generation
  // I'm not quite sure if next line is correct.
  // But it passes all testcases, at least.
  // Change to `n=n/4-r*4` would somehow ensure
  // its correctness, but also make it slow as hell.
  n-=r*3 // A smaller search bound for next generation
 )
  for(
   o=[ // All points visited, stored by key
       // For example, if (3, 4) is visited
       // o['3,4'] would be something truthy
    x= // Current x
    X=0, // Current x axis direction
    Y= // -Y is current y axis direction
    y= // current y
    s=1 // current circle area is s*PI
   ]; // Values initialized in Array o are harmless garbage
      // As index `0` or `1` is not in `x,y` format
   x<n; // Search in the bound
   o[[x+Y,y+X]]?0: // If the left side point is not visited
   [X,Y]=[Y,-X] // we turn left
  )
   if(!( // !(a||b) iff !a&&!b, known as De Morgan's laws
    o[
     [x+=X,y-=Y] // Move one step forward
    ]= // Mark current point visited
    // Is there a circle intersect with current one (if
    // we placed it here)?
    C.some(([X,Y,R])=>Math.hypot(X-x,Y-y)<R+r,r=s**.5)||
    // If no such circle, we need to place a circle here
    s++-k| // Is current area equals to user input `k`?
           // Increase the area for next circle by `s++`
           // `|` do not use short-circuit evaluation
    G* // Is current generation counted down to 0?
    C.push([x,y,r]) // Push it to list of circles
                    // C.push(...) always returns positive
                    // So multiply by G is harmless
   ))
    return[x,y] // Return current circle if it is asked for
}

```
> 8 votes

# Answer
# JavaScript (ES2020), ~~417~~ ~~338~~ ~~331~~ ~~323~~ ~~321~~ ~~318~~ ~~316~~ ~~304~~ ~~303~~ ~~290~~ ~~283~~ ~~273~~ ~~269~~ ~~261~~ ~~257~~ ~~252~~ ~~247~~ ~~244~~ ~~237~~ ~~234~~ ~~238~~ ~~234~~ ~~207~~ ~~206~~ ~~205~~ ~~200~~ ~~194~~ ~~193~~ ~~186~~ ~~182~~ ~~183~~ 182 bytes

```
G=>K=>eval('for(l=[];G--;)for(x=y=d=0,L=t=i=1,X=l[G]=[];t--,K<<3*G>=i;d%2?y+=2-d%4:x+=1-d%4,t||=L+=d++%2)X[l.some(Z=>Z.some(([M,N],R)=>Math.hypot(M-x,N-y)<R**.5+i**.5))||i++]=[x,y]')

```

Try It Online?

Severely golfed. Very inefficient. Thanks to @Neil for getting rid of all the spare bytes I had lying around, and @tsh for removing a lot more. Takes G 1-indexed and K 1-indexed. -1 byte thanks to ophact.

Somehow beat @Arnauld, ~~but still losing to @tsh by a lot~~ somehow outgolfed tsh as well.

# Explanation

Slightly different to actual code.

```
G =>                         // A function taking G (generation)
K => {                       // and K (circle number)
  for(                       // Start a loop...
    l = [];                  // l = 2d list of circles we've already found, starts empty
    G--;                     // Looping G times...
  )
    for(                     // Another loop
                             // Initialise some variables
      x = y =                // x, y = current coordinates in the spiral
      d = 0                  // d = direction of current leg of spiral, initialise them all to 0
      t =                    // t = distance to end of spiral
      i =                    // i = current radius
      L = 1,                 // L = total length of current leg of spiral
      X = l[G] = [];         // Add an empty list to l, which gets assigned to X.
      t--,
      K << 3 * G >= i;       // Every generation, search for 8x less circles (probably enough, can always be increased)
      d % 2 ?                // If moving vertically
        y += 2 - d % 4       // Change y
      : x += 1 - d % 4,      // Else change x
      t ||=                  // If t is falsy, set t to...
      L +=                   // L incremented by...
      d++ % 2                // direction modulo 2
    )
    l.some(                      // Do any values in l have the property that...
      Z=>Z.some(                 // Any of their values have the property that...
        ([M,N],R) =>             // (M, N = coords, R = radius)
        Math.hypot(M - x, N - y) // Is the distance to the point we're on right now...
        < R ** .5 + i ** .5      // Less than the sum of their radii?
      )
    ) ? 0 :                      // If not, we can place a circle.
    X[i++] = [x,y]               // Increment i (radius of circle we're trying to place), and append the coordinate to X
                                 // The above is returned when the loop ends because i is too large.
}

```
> 14 votes

# Answer
# JavaScript (ES7),  ~~319~~  309 bytes

Expects `(g)(k)` and returns `[x,y]`.

The formula for the spiral coordinates was inspired by this answer from Neil.

```
g=>k=>{a=[];p=[];r=[];H=Math.hypot;F=n=>{while((j=p[n]=-~p[n],C=_=>((i+2>>2)-i%2*j)*~-(i--&2),x=C(i=(--j*4+1)**.5|0,j-=i*i>>2),y=C(),n)&&a.every(([N,X,Y])=>~N+n|H(X,Y)<2*H(x,y))&&!F(n-1,p[n]--)||a.some(([_,X,Y,R])=>H(X-x,Y-y)<R**.5+q**.5,q=-~r[n]));a.push([n,x,y,r[n]=q])};while(~~r[g-1]<k)F(g-1);return[x,y]}

```

Try it online!

### How?

One tricky point in the challenge is to figure out how many circles of generation \\$n-1\\$ must be processed before we can start generation \\$n\\$.

In this implementation, we don't attempt to put a new circle of generation \\$n\\$ at \\$(x\_0,y\_0)\\$ until there's at least one circle of generation \\$n-1\\$ at \\$(x\_1,y\_1)\\$ which is at least twice as far from the center of the spiral:

$$\sqrt{{x\_1}^2+{y\_1}^2}\ge2\times \sqrt{{x\_0}^2+{y\_0}^2}$$
> 14 votes

---
Tags: code-golf, sequence, geometry, packing
---


# Question
Title: Regex Golf: Regions of Italy vs. States of USA
We've already got a meta-regex-golf problem as inspired by the xkcd comic

But, this regex golf looks fun, too! I want to distinguish between the states of the US and the regions of Italy. Why? I'm a citizen of both countries, and I always have trouble with this*.

The regions of Italy are

```
Abruzzo, Valle d'Aosta, Puglia, Basilicata, Calabria, Campania, Emilia-Romagna, Friuli-Venezia Giulia, Lazio, Liguria, Lombardia, Marche, Molise, Piemonte, Sardegna, Sicilia, Trentino-Alto Adige/Südtirol, Toscana, Umbria, Veneto

```

and the states of the USA are

```
Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming

```

Your job is to write a program which distinguishes these lists with a regular expression. This is a new game, so here's the

**Rules**

* Distinguishing between lists must be done with a single matching regular expression.
* Your score is the length of that regular expression, smaller is better.

To be clear: all work must be done by the regular expression -- no filtering, no replacements, no nothing... even if those are also done with regular expressions. That is, the input should be passed directly into a regular expression, and only the binary answer (match / no match) can be used by later parts of the code. The input should never be inspected or changed by anything but the matching expression. *Exception*: eating a newline with something akin to Ruby's `chomp` is fine.

Your program should take a single entry (optionally followed by `\n` or `EOF` if it makes things easier) from either list from stdin, and print to stdout the name of that list. In this case, our lists are named `Italy` and `USA`.

To test your code, simply run both lists through it. Behavior may be undefined for strings which do not occur in the list.

**Scoring Issues**

This might have to be done on a language-by-language basis. In Perl,

```
m/foobarbaz/

```

is a matching regular expression. However, in Python,

```
import re
re.compile('foobarbaz')

```

does the same thing. We wouldn't count the quotes for Python, so I say we don't count the `m/` and final `/` in Perl. In both languages, the above should receive a score of 9.

To clarify a point raised by Abhijit, the actual length of the matching expression is the score, even if you generate it dynamically. For example, if you found a magical expression `m`,

```
n="foo(bar|baz)"
m=n+n

```

then you should not report a score of 12: `m` has length 24. And just to be extra clear, the generated regular expression can't depend on the input. That would be reading the input before passing it into the regular expression.

**Example Session**

```
input> Calabria
Italy
input> New Hampshire
USA
input> Washington
USA
input> Puglia
Italy

```

* Actually, that's a lie. I have never had any trouble with this at all.

# Answer
> 11 votes
# Perl - ~~51~~ 36 bytes (for regex)

```
print<>=~/.A|ise|net|te|z.o|[cp]a|[lr]ia|r[cd]/?"Italy
":"USA
"

```

~~Nothing special, but may as well post it, because it's different to other 51 bytes solution.~~

Or alternatively, shorten my already short solution by 15 bytes. This wins for now, I think.

# Answer
> 8 votes
## Perl, 40 chars

Approaching this from the other direction, i.e. matching the U.S. states:

```
[DNIOWy]|ss|M.n|^A.*a|or|[aguh]i|[sth]\b

```

The only Perl/PCRE-specific feature in the regexp is the `\b` word boundary anchor, which I used instead of the `$` end-of-string anchor to let it match "South Carolina".

Here's the regexp in a Perl one-liner for testing:

```
perl -nE 'say /[DNIOWy]|ss|M.n|^A.*a|or|[aguh]i|[sth]\b/ ? "USA" : "Italy"'

```

# Answer
> 7 votes
# Regex (POSIX ERE), 28 bytes

Matching the regions of Italy:

```
[eldrz]..$|[cpVS]a|-|[hst]e$

```

Try it online!

Since we're being scored on the length of the pure regex, it just makes sense to show that alone above. The TIO test harness uses bash and egrep, but practically any regex engine would work. The only thing that makes this require POSIX ERE instead of POSIX BRE are the unescaped `|` alternative separators. Here is a bash oneliner to apply it:

```
egrep -q '[eldrz]..$|[cpVS]a|-|[hst]e$'&&echo Italy||echo USA

```

I used regexp-golf-coffeescript, with a little parameter tuning, to brute-force this.

You can experiment with deleting characters from the character classes or deleting alternatives in the TIO to see how many correct matches are lost by doing so. For many, it's just one each.

There may be further optimization possible. The script I used only searches the space in which a single character class is used per alternative, but some regex golf problems of this type benefit from multiple character classes in a single alternative, like `[bgr].[ei]`. However, given the characteristics of this data set, I expect that the benefit, if any, would probably be no more than a couple bytes.

# Regex (POSIX ERE), 41 bytes

Matching the states of the USA:

```
[IfKNOWwhy]..|[kamed].$|t$|iz|ta.|[guaM]i

```

Try it online!

# Answer
> 5 votes
# Ruby (plain regex), 44

```
$_ = gets.chomp
puts /'|-|(([^gn]i|gn|at)a|[hst]e|to|zo)$|To|La|pa/ ? "Italy" : "USA"

```

You know what? Case sensitivity is the best start-of-word anchor.

I'm not sure, but I think I owe the `pa` to Hax0r778's answer.

# Answer
> 3 votes
## Perl - 51

```
(<STDIN> =~ m/'|-|ru|pu|at|pa|az|gu|mb|rc|ie|rd|ci|os|abr|mol|ven/)?printf("Italy\n"):printf("USA\n");

```

# Answer
> 3 votes
# JavaScript 42

`alert(/at|gn|mp|sc|-|'|((zi?|t)o|[hts]e|[lrd]ia)$/g.test(prompt())?"Italy":"USA")`

I was initially going to work this out from the USA side, as eliminating KWXY from the USA list strips a lot of the States away... But Italy had it bested by a good 17 characters...

If we go with fat arrow notation we can reduce this to a simple function with a return variable.

`r=s=>/at|gn|mp|sc|-|'|((zi?|t)o|[hts]e|[lrd]ia)$/g.test(s)?"Italy":"USA"`

```
> r("South Dakota") // USA
> r("Puglia") // Italy

```

---
Tags: code-golf, regular-expression
---


# Question
Title: Generate Brainfuck for the numbers 1–255
Write a program that, for the numbers 1 through 255, prints out BF code that will produce the given number in some byte of the array, plus a newline.

For example, the first four lines of the output could (and most likely will) be:

```
+
++
+++
++++

```

The winner will be the smallest: `source code + output` (in bytes).

**Clarifications & Revisions**:

* BF programs use wrapping cells.
* The output BF program must terminate with the only non-zero cell being the cell containing the number.
* Programs must be output in ascending order.
* Outputting a program for 0 is optional.
* Negative data pointers are not allowed. `<` at the first pointer will do nothing. (leave a comment if it would be more appropriate to have it throw)

# Answer
# Perl 6, 224 + 3964 = ~~5834~~ 4188 bytes

```
map {say (.[0]~'['~.[3]~'>'~.[1]~'<]')x?.[1],'>'x?.all,.[2]}o*.min({$_>>.abs.sum+6*?.[1]})>>.&{<- +>[.sign>0]x.abs},classify({0+|(grep(*%%1,(((256 X*^4)X+.[0]%256)X/-.[3]))[0]*.[1]+.[2])%256},[X] |(^27-13 xx 3),-7..-1){^256}

```

Try it online! (may timeout. Change the `^27-13` to `^25-12` to speed up slightly at the cost of some extra output)

Outputs the shortest code in the form `*>[*>*<]>*`, where each `*` is a certain number of `+`s or `-`s. There are some extra tweaks like removing the loop if it is not needed, as well as trailing `>`s.

As far as I can tell, the output is the most golfed for this particular format.

### Explanation:

```
([X] |(^27-13 xx 3),-7..-1)        # Define the search space as the cross product of:
                                        # -13 to 13 for:
                                            # Initialisation     +++>
                                            # Change in target   [*>+++<]
                                            # Last change        >+++
                                        # And -7 to -1 for the change in start [-->*<]
  .classify({                  })  # Group them by calculating
                  (256 X*^4)                         # Each of the multiples of 256
                 (          X+.[0]%256)              # Plus the initialisation
                (                      X/-.[3])      # Divided by the change in start
      grep(*%%1,                               )     # Filter out the whole numbers
                                                [0]  # And take the first value
          # This is the amount of times the inner loop will execute
          # Being Nil, converted to 0 if it is an infinite loop
      *.[1]              # Multiply by the change to the target cell
           +.[2]         # And add the final section
     (          )%256    # And modulo the whole lot by 256
                     +|0 # And floor it just to keep the .0 out
classify(                   ){^256}     # Take the corresponding groups in order
   .map(                             )  # And map each to
        *.min({                    })   # Find the minimum by:
               $_>>.abs.sum             # The sum of the absolute values
                           +6*?.[1]     # Plus 6 if it loops
      >>.*{                   }    # Then map each value to
           <- +>[.sign>0]          # + or - depending on the sign
                         x.abs     # Repeated by the absolute value
   {                    }o              # And pass this to the next code block
    say                       # Print
        (.[0]~'['~.[3]~'>'~.[1]~'<]')             # The loop section
                                     x?.all       # If it is needed
                                           ,.[2]  # And the final part

```
> 16 votes

# Answer
# Brainfuck, ~~77~~ ~~75~~ 73 + 32894 = 32967 ~~32969~~ ~~32971~~ bytes

```
++++++[->+++++++<]>+>++++++++++>+[>+[-<<<.>>>]<<.>[->+>+<<]>>[-<<+>>]<<+]

```

Try it online!

output is the simplest possible

```
+
++
+++
++++
...

```

---

explanation:

```
++++++[->+++++++<]>+ set cell 2 to 43 (ascii of plus)
>++++++++++ set cell 3 to 10 (ascii of new line)
>+ set cell 4 to 1
[
    >+ increment cell 5
    [
        -<<<.>>> decrement cell 5 and print a plus (content of cell 2)
    ] until cell 5 == 0
    <<.> print a new line (content of cell 3)
    [
        ->+>+<< move value of cell 4 to cell 5 & 6, setting cell 4 to 0
    ]
    >> goto cell 6
    [
        -<<+>> move it's value to cell 4, setting cell 6 to 0
    ]
<<+ increment cell 4
] exit when cell 4 goes beyond 255 because cell contains C uchar meaning 255 + 1 == 0

```
> 16 votes

# Answer
# Stax, score ~~4751~~ 4783 (812 bytes \+ 3971)

```
ç♥←Ä§òqε↓F"QS₧9(2╤↑▌T~│áZk♣☺nàK╬l•▼2≡→fZ⌂▼├▄<ÖΘá6≈¡K"B∩₧∟µ#°ôQí⌡B2ô§↕*∩)V╕EôD=)O╥T⌠û◘¬dⁿ┤☻∞ô↓♫√○¬z.â\²╕ùHÑ~≡M√☻:EzLƒ→B{O◙ΔΦ_S┼╤g°▓─+dï-┌└α½╥ôRù♠3f½⌐▀Pösúô₧f☻■Aε→τΓ£╒fε▬▬►EÜ%¬╧←y═←{╤╒öú5Ñ╡♀^α☺╨▼$kEÑ■µjh≈↕█Cªü←Z#∟gV↓►S3≥╟╗K‼╞.N|⌠↨╣}5H↕ê;±↓♣≤Tj█'x╒·±ΩßL;ª$Å÷ÑPIδ`◘▌╦┼╡<√▌{òE√PPQ/h@8kq/ÖΓb6╡]≈╤æ░╣{┌‼¢ÜαT├#ΓCN∞*╬⌡↕ÜVX←Ä)◘ù⌂ëøön╗)ôö∙╬⌠☻↨F¢X╓SÅ¼9¡φö^⌂iøFB/┌º▼┤3¶☼Zëôû⌡ôΣfcäéi╣⌠"↨√$,.ë═┴↨Φz⌡τ¢S╜{╨)z:╦@}♦*│P±Æ1x╒ΦP▄◄·╢∙xF╢cá<T╗7;▐≤←÷╛╢;½▲§║│≈⌂ƒ*'F♂☼ùrT╞·╨nG∙=♦`;á$≥┼Ω▬≡aû┼☺╥ò♥R╧╖█▓uìf↕ñ∟φÖ♣°≥←▐G▀╗┘┴÷a*▐♂9╝┬çG─⌠ñ≈☻K·⌐α⌠╡↑!≤≡¡qßτú=Θ≤C░°¡ƒ╛>╨RP○v¡I♦◘╣ô6â₧scÉ♀╣+HO┌☼<♀»?£┴≥ï½.ohaë║ëb┼âù²┌─┬]░ΘQ¥τ┘q▼$v╞Ñ╒æ±tXƒ♪>SC▌LVWª■z↑¶ßΩû↕'L╓BÅï;↑ΦB2.G╞╜&╓π♥1¥0^B0ª≤5e|☼τ5╩╘µåΩ╬◙☻xª└í∞$┐☻∙d▼}╒R⌠AU@Ω♥δÇi0î┴ ↕ù‼☼ƒ┌Aw£╧à7û«W3ùΦ╚A)P○♥Xn⌂øôEΦGB≥╢g[∟a(◘&¥◙─♂→A@┴ö≡↕9PZK║î⌂eóë≥─Åⁿ1‼╢▀ó╙ª▲╒π╗tΣ4○√;■<ä║äqñ8╠T/»q\→↔1ç°ΘZδV♀EçZ▄g┤Å╤ ┴àúJ║wµ$▄«N

```

Run and debug it

I started with the optimal published programs.
I used some regex-fu, to limit it to the shortest programs that use at most 2 cells. Then I trimmed any trailing `<` or `>` characters. I think this is a possibly conservative way to ensure that there are no extraneous non-zero cells at program termination. Then I ran it through an experimental stax program I wrote to generate stax programs for fixed kolmogorov-type output.
This program works by repeatedly applying string replacements. At each step, it looks for \>1 length substring that occurs most frequently and replaces it with an unused character.
> 10 votes

# Answer
# Charcoal, ~~707~~ ~~698~~ 410 + 3627 = ~~4334~~ ~~4325~~ 4037 bytes

```
ＵＴ≔”}⊞Ｊ5±)↷γ²⁼⎇⦃<✂f^⊗Ｌ…¬⁻←«θ↥v⊙^≔¶υＳψVτ16⁷·9I⌕↘;⦃@Pmt↙ ｜TＬ ‹.bＥ^↷Ａm⟧←⪫✂«ＧＩχ¤⟲V⁻PÀ$χ¹'$↙‖%S³6◧N=$kＨＩpQ×ïu｜%÷I↖➙⁸≔Wλ¹ê8⌕dNK‽3H∨↥γh➙↘⊙⊕“~Oj↨-⬤…⊟⁺§◨ＣＢ℅Ｐ⌕KＮＥAR№K⬤Ｘ"¬Ｓ⎇⧴V⁻±6⁼✂kι×ＣÀ⊞‴≡w↓γ=`→P5η1Ｃ⊖ＯSoNυs⊘$M↙êαη↖φ¡¿:θ-γ“rＪW%Ｅ(7<w¤Ｕφ´ρＨπ←SＸ↔τ↧%<Ｔº⎇0gθμ↓⌕；σw⌈pL;Ｙ↘ＹΠ⊙>ξＬzλ↓⁸ι⎚｜⌕ΠP″M³⧴⬤¦➙⟧⌕/δ；↥⁻ºJK⌊≡<⊖λ✳Ｊκ⟲➙ξ⭆｜^Σ*βＭπ⍘⊟；ÀＵ÷‹⭆◧�ωκ?σηkＹＯδO/Ｂº？lＡnaＫ{*Ｋaκ◨+↧aSφ0q‖Ｂ/φx⊘⌕«³ψü✂‹º≡/yc⁴＆Ｊ↙Ｓ²~⎇z§‖$SＰ≧”θＧ↘←¹⁴+⮌⪪θ⸿↑Ｆθ§⁺+-ι⌕-+ιＧ→↙¹⁴-

```

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

```
ＵＴ

```

Turn off space padding.

```
≔”...”θ

```

Assign a large compressed string consisting of @JonathanAllen's answers for `-128`..`-15` but with `+` and `-` signs transposed.

```
Ｇ↘←¹⁴+

```

Draw a triangle of `+`s of side 14, which generates the correct results for 1 to 14. The cursor is left in the bottom corner, although the trailing return on the compressed string will move the next output to the next line.

```
⮌⪪θ⸿

```

Split the large string on return characters and print each substring in reverse order, thus generating the results from 15 to 128.

Move up a line so that the result for 128 is overwritten by the negated result for 128.

```
Ｆθ§⁺+-ι⌕-+ι

```

Loop through the string transposing `+` and `-` back again so that they generate the correct results for 128 to 241.

```
Ｇ→↙¹⁴-

```

Draw a triangle of `-`s of side 14, which generates the correct results for 242 to 255.
> 9 votes

# Answer
# Jelly, 1224 + 3716 = 4940 bytes

```
⁾+-ẋ€Ɱ14ZY€U0¦j“6VⱮ×ė7¬(Ị¢ẋṀⱮM⁵Ñ¬kbvœ⁸½ẋƓ0⁽ṖçḟŻßɓẉḷ0Ƙ¥@ⱮZĊⱮ{ṫṇØ"ỵðẓ⁵!ḳqḄƬiỴƥṇØm@ɗẆḅƥƲ⁴ŀ-5¦€ÑɓZĖ/gPṄḌ!ẹ$ḞıƒĿỵ⁷£Q.%¦ẊiUı-M⁹ƈxṁ,CsḲtÆƇỴṄĿiæEṛⱮẒʠþƘ%ƘƙṾ ('ȥ€½⁵ḥ+,þ@ẇ&ạV|ĊuAYḃfṖƘLƥQtPƬivxHj)Ṇɓ5JṘØẓæĿøɗjḥrñþa®OṅḍṪ¥=ɼġċṫßṬỌƈrUẉçŻ½\=]€ʂ_ⱮṖ¥Ƥȥ6SṡÆcạdn;ṅⱮDɦ⁹ṢAy)~Ḷ`ẒẓMTİṂḋ|ẉ]Wɠ¿⁾Ṣ|ḷ6hẸƒⱮQ1ẏƝC@Ŀ!ʠ⁽ṃ@ƓŒQ3@ƝḊñçcZ\¥3Z¤~çD>ċọuⱮȦAẈⱮ%L3Æ¢ḞtĖė!ƇtñṪɓẓ¥Fṅ⁵shB'wṪẸ¦ṄÞṭ³ʂḶƊ³iȧṂRœŒƤ\r1Çwi6ŀỵɼḃa⁵Ṣ_Q⁸Ẹ'{|\+Æ®|ḤcʂÑ/Ɓz¶ɦÄ!ʂ"Ẋ ẓĠĠ⁷⁵QƝ¶%ṙƇḋ[^j&W×*°ḳçʂSżḊⱮ⁻IȦṄXȥlẋḅ7;⁺ḃİÞÆðLX¢1K£€Ä&X½VȮ(;Q£ḞḢ¹zG+ṅ¹LḥW³ḅd@^ẊḶJ¹T8ṛ($ȧṢzq,Ṫ⁻ȥ{Ṛ"Ḍ®Ä8QḋþɼȮhỵB"Ḍ⁶ȧZ⁵ẒNɓḃȧ¶Ƒð$Ẇ/"Eṭ*I:ØḃL}<KȦ+ṣ¥x&Ṇ£Œṫḋġ0lİḍ¿H£(ỌƝ×^Ḃ°⁽⁼UƭĠḥkQð7ṫƤżȷƘxjƑRḣqƒ$HƬ7ḳ-JµnṇṣðXŻİẉbSu×]bṾ0ƊHßçQh⁸°ƒɦSCñ_⁾ʂC⁼Ġø⁵SAʋƊİ¡⁴ÄḋẸḶwȧZẈĠ7rṀẏẉṖa¤ɱELƝȧẈṣṄk]d⁹øṇÞṡ.ạtƥṢḅ⁺ṂLpÑƘṄṡḍ⁵,Ç¤$Ọ8ṛuṚvAṖÑ1!vƤD3ß¶ʂÐ°]EÞUĠ€ḋḲ⁸¬r`YḊ0ṙ5ċmṅȯ*ɲU÷pƭẉṭȦB¹ɦSNɱ)]ĠṾʋ³Øḟ23ṭð#ẆuẎṬṫVɠ(ỊỊQɼF}ịƒ$Ẏ_Ṡ'ḳOLc?ṾŀẊẎṆ⁵p"VẏAȮ⁴ⱮȦ®e®Ɱi"ÇJẊ4ñḍḲY]ḌḌẓ⁺ƙ"iṄḅoLṙfOS&}HGɼĖİĠḷuḃ³ṡıḳỊẹzq⁶ƈ£ċHZɱ.#⁶ḟUṗŀȮṘḶḲ]@¶+ḊĖ8ĖṆɗçŻŀ®ṭẇƓḄḷıM@⁷²36ɲṗ¡ḂḊ'Ṿ⁵ėƙṘ-⁺µʠṡṂ[_¤ḥṢ]ṘÐḤ½ḟ4ȷ}E¹Ṙb⁹ḅḢ¹hƬZ§Ẏẹ÷Æ$ḅoĖẉ⁹ịJ.ȥḊẋʋṄȯ1<ẎṄḲṛœ"æ)ḥ8)ḤlñA⁾%⁶LỴ⁶M4Ṙ\`ỵƊȥŀƒ⁷ḌƬƙḳƑ⁴vʂ⁻ðQpñḷḳṄœ>ṪỴƭƙɓ3[&Ḅzḅ<⁾µİṪȧ⁹C>ẹ{ẈÐlC&j?LṆṛ⁽æȤið<⁽$Ḋ7⁻FṡḅɓɱḂJoPŻẆṃṛḂ¹ẓð[1eƘ2T⁶ḟɼ7P~©ṚṙE8RƒṬẹLœẇẸịøḷ*⁾²ÄƓy€VƈɱNSẏẓÑ¶pƲḞḅX⁹ọaœ<aỴTĠ^ðƑṙẊḅOḥŀG4ị¤ÑėÐịʠɗ=YṚċẋĠżẉịṪṁtḳṪ{ṬṃıızD/ĊvȤpḣðÐ¡þfÞ⁶ỵỊµṅḷÄ÷Vẇ\Ạ$-§OẠn^ȯfẎlḊd⁶ni¥ẓɱn¶’ṃ“¶><-][+”¤⁷

```

A full program.

**Try it online!**

### How?

Almost entirely compression of current bests on esolangs which leave only a single non-zero, with trailing tape moves removed. There is probably a way to evaluate a subset of BF programs such that they will terminate and yield the shortest solutions that'd beat this naive program. There may well also be a way to beat this by a smarter pattern-based or factorisation-building program.

```
⁾+-ẋ€Ɱ14ZY€U0¦j“ ... ’ṃ“¶><-][+”¤⁷ - Link: no arguments
⁾+-                                - list of characters ['+','-']
    €                              - for each:
   ẋ                               -   repeat
     Ɱ14                           -   mapped across [1..14]
        Z                          - transpose
         Y€                        - join each with newline characters
           U0¦                     - reverse the rightmost
                                   -   (now we have ["+\n++\n+++\n ...","... \n---\n--\n-"]
                                ¤  - nilad followed by link(s) as a nilad:
               “ ... ’             -   a really big number compressed as base 250
                       “¶><-][+”   -   list of characters ['\n','>','<','-',']','[','+']
                      ṃ            -   decompress - use as base 7 digits [1,2,3,4,5,6,0]
              j                    - join (the list ["+\n++...","...--\n-"]) with that
                                   - implicit print
                                 ⁷ - a newline character
                                   - implicit print

```
> 5 votes

# Answer
# SuperMarioLang, 231 + 32894 bytes

```
)
))++>(>+)*>[!((&(>[!*>-)-[!([!
===+"="==="=#===="=#="====#==#
+++<(       )    !+< !  ( <
+===+ (   - .    #=" #===="
>[!+( (   !(<
"=#++ (   #="
- (++ !.))    )))            <
) +++ #======================"
+ +++
+ ++!
!+<=#
#="

```

Try it online!

This sure can be golfed more, as the output is the most basic for brainfuck, but it took me all day to write this answer (my three children leave me little time to spare) and I'm proud that at least I managed to achieve this.
> 5 votes

# Answer
# Python 2, 70 + 8428 = 8498

-2 Bytes Thanks to A\__!
-20 Bytes Thanks to Jonathan Allan!
-229 Bytes by putting the number in the second cell
-1000ish bytes by switching from 16 to 9

```
p='+'
i=1
exec"print[p*i,i/9*p+'[>'+p*9+'<-]>'+i%9*p][i>20];i+=1;"*255

```

Try it Online!

Output
> 4 votes

# Answer
# Ruby 271 + 5363 = 5634

```
1.upto(255){|n|r=n>(o=n>128?256-n:n)??-:?+;puts o>20?(s=o.to_s(i=(3..9).find{|i|!(s=o.to_s i)[1..-2][s[0]]}).bytes;s[-1]+=s[0]%8;(s[1,9].reverse.map{|c|(c-=s[0])<0??-*-c:c>0??+*c:?-}*?>+'[>'+?+*(s[0]%8)).tr(n>o ?'+-':'','-+')+'[-<'+?+*i+'>]<<]'+(s[-1]>s[0]?'':?>+r)):r*o}

```

Try it online!

Converts each value to the smallest base which doesn't contain ~~a zero~~ its initial digit at any other place, and then converts from that base. Values greater than 127 are calculated as their inverses.

---

**Non-Wrapping, 221 + 5888 = 6109**

```
1.upto(255){|n|puts n>20?(s=n.to_s(i=(3..9).find{|i|!(s=n.to_s i)[1..-2][s[0]]}).bytes;s[-1]+=s[0]%8;s[1,9].reverse.map{|c|(c-=s[0])<0??-*-c:c>0??+*c:?+}*?>+'[>'+?+*(s[0]%8)+'[-<'+?+*i+'>]<<]'+(s[-1]>s[0]?'':?>+?-)):?+*n}

```

Using the same approach as above, with non-wrapping cells.

Try it online!
> 4 votes

# Answer
# JavaScript (Node.js), 691 + 3627 = 4318

Using the same approach as @Neil's Charcoal answer, and therefore also based on @JonathanAllan's Jelly answer.

```
_=>(a=require('zlib').inflateRawSync(Buffer('bZXRsQMhCEX/0wpDB4yNOPbfxoMLKLAvs8lyQBEBDf2I9MHXf+I3X/f9hCJVsckdBgH3gih8YHT80Kpj01zQ7dUZb9osZ0Fzfvra+qiCl6GaqTB9vTdvNn2TjiaVjvBQKG5mHS/mMBGrywc1Vl2eIzqbwFPReVjJo1+I3mLfbAOYY201Sm491vaxDM+Vh9WSaJtgfBDYUHQeVrKkqzMEaYMrWpgbMS7MtIlIry3DgztWahbqNPElykKItD4e1hgN8qyrHA1CJ/dC5Imz3WS5PeDKDdGKDvS8WqBq+reSd4lH2Gtjcr9W95ydm/8kcaaRPsNpMiHS1kjW8qWAOsFmWEdHeiw/kenG1zdqzR0bVXhy0VKVPQVesFNloU4TI5nsp4qzunLytsCheK4B2Gz0UeXobM+M3Q2NcXhx+GlF389GH53eWr31utUf90W02MVu89LZs45IhP/Qc6jx9dYoCs8W1d4vKHHO8wJ9l8y4Vd614g788IzrViKArok/CmguX/KLqSl+c7h3STZcxUYVnvwH','base64'))+'')+`
--[>-<--]>-
`+[...a.split`
`].reverse().map(s=>s.replace(/[-+]/g,c=>c>','?'+':'-')).join`
`

```

Try it online!
> 4 votes

# Answer
# brainfuck, 3785 + 4120 = 7905 bytes

```
-->>>->>->>->>+>>->>->>->>-->+>->>->>->>->+>->>->>->>>+>->>->>->>->>>>-->+>->->>>>>-->+>->->->>>>->+>->->->>>>-->+>>->>>>>-->+>>->+>>>>-->+>>->->>>>->+>>->>>>>->+>>->+>>>>->+>>->->>>>>+>>->->>-->->->+>->+>>>-->->->+>->+>->>-->->+>+>-->+>>>-->->+>+>-->+>->>-->->>+>->+>->>-->->++>+>-->+>>>-->->++>+>-->+>-->->-->->+>+>->+>->>-->->+>+>->+>->>-->->>+>>+>>>-->->>+>>+>->>-->->++++>+>-->+>->>-->->++>+>->+>>>-->->++>+>->+>->>-->->+>+>>+>>>-->->+>+>>+>->>-->->+++>+>->+>>>-->->+++>+>->+>->->>++>->->+>>-->->>++>->->+>>->>>++>->->+>>->>>++>>>-->+>>>>++>>>-->+>+>>>++>>>-->+>>->->++>>>+>>->->->++>>>+>>-->->->++>>>+>>->>->++>>>+>>>>->++>>>+>>+>>->++>>>+>>-->+>->++>>>+>>+>->>+>>>>>>->>+>>>>>->->>+>>>>>-->->>+>>>>>->>>+>>>>>>>>+>>>>>+>>>+>>>>>-->+>>+>>>>>->+>>+>>>>>>+>>+>>>>>->>++>++>>>>>>>++>++>>>>>+>->->+>>>->+>>->->+>>>->+>->->->+>>>->+>-->->->+>>>->+>->>->+>>>->+>>>->+>>>->+>+>>->+>>>->+>-->+>->+>>>->+>->>->+>>->->+>>>->+>>->->+>+>>->+>>->->+>>->++>+>>>>>->->++>+>>>>>-->->++>+>>>>>->>++>+>>>>>>>++>+>>>>>+>>++>+>>>>>-->+>++>+>>>>>+>++>-->+>>>>>>++>-->+>>>>>->++>-->+>>>>>++>->-->+>>>>>+>->-->+>>>>>>->-->+>>>>>->->-->+>>>>>-->->-->+>>>>>->>-->+>>>>>>>-->+>>>>>+>>-->+>>>>>-->+>-->+>>>>>->+>-->+>>>>>>+>-->+>>>>>+>+>-->+>>>>>++>+>-->+>>>>>+++>+>-->+>>>>>++++>+>-->+>>>>>>++>>+>+>>>>->++>>+>+>>>>++>->>+>+>>>>+>->>+>+>>>>>->>+>+>>>>->->>+>+>>>>-->->>+>+>>>>->>>+>+>>>>>>>+>+>>>>+>>>+>+>>>>-->+>>+>+>>>>->+>>+>+>>>>>+>>+>+>>>>->->++>+>->->>>-->->++>+>->->>>->>++>+>->->>>>>++>+>->->>>+>>++>+>->->>>-->->++>++>+>>>>->>++>++>+>>>>>>++>++>+>>>>->>+>>-->+>+++>+>-->->+>>>+>->+>->>+>>>+>->+>->>+>>-->+>+>+>->->+>>-->+>->+>-->->+>>-->+>->+>->>+>>-->+>->+>+>->+>>>>+>>>->+>>>>+>>->->+>>>>+>>-->->+>>>>+>>->>+>>>>+>>>>+>>>>+>>->>+>>-->->+>>>>+>>-->->+>>+>>+>>-->->+>>-->+>+>>-->->+>>->+>+>>-->->+>>->>+>>>->->+>>>+>>>->->+>+>>+>>>->->+>->>+>>>->+>+>->>+>>++>->->+>>>+>>++>->->+>->>+>>>->+++>+>-->->++>++>->->>>->>++>++>->->>>>>++>++>->->>>->->++>+>+>>>>-->->++>+>+>>>>->>++>+>+>>>>>>++>+>+>>>>+>>++>+>+>>>>++>->>+>->->>>+>->>+>->->>>>->>+>->->>>->->>+>->->>>-->->>+>->->>>->>>+>->->>>>>>+>->->>>+>>>+>->->>>-->+>>+>->->>>->+>>+>->->>>>+>>+>->->>>+>+>>+>->->>>++>+>>+>->->>>++>++>-->+>-->->>>+>++>-->+>-->->>>>++>-->+>-->->>>->++>-->+>-->->>>++>->-->+>-->->>>+>->-->+>-->->>>>->-->+>-->->>>->->-->+>-->->>>-->->-->+>-->->>>->>-->+>-->->>>>>-->+>-->->>>+>>-->+>-->->>>-->+>-->+>-->->>>->+>-->+>-->->>>>+>-->+>-->->>>+>+>-->+>-->->>>++>+>-->+>-->->>>+++>+>-->+>-->->>>>->++>+>-->->>>->->++>+>-->->>>-->->++>+>-->->>>->>++>+>-->->>>>>++>+>-->->>>+>>++>+>-->->>>-->+>++>+>-->->>>->->->+>-->+>->+>-->->->+>-->+>->+>->>->+>-->+>->+>>->->+>-->->->+>->->->+>-->->->+>-->->->+>-->->->+>->>->+>-->->->+>>>->+>-->->->+>+>>->+>-->->->+>-->+>->+>-->->->+>->+>->+>-->->->+>-->->++>++>-->->>>->>++>++>-->->>>++>->>+>-->->>>+>->>+>-->->>>>->>+>-->->>>->->>+>-->->>>-->->>+>-->->>>->>>+>-->->>>>>>+>-->->>>+>>>+>-->->>>-->+>>+>-->->>>->+>>+>-->->>>>->->++>-->->+>>->->->++>-->->+>>-->->->++>-->->+>>->>->++>-->->+>>>>->++>-->->+>>+>>->++>-->->+>>-->+>->++>-->->+>>->->>++>-->->-->+>-->->>++>-->->-->+>->>>++>-->->-->+>->>>++>+>>+>>>>>++>+>>+>>+>>>++>+>>+>>-->->>>+>++>+>->->>>>+>++>+>->-->->>>->++>++>->->>>>->++>++>->-->->>>>++>+>->->>>>>++>+>->->>>>++>++>>->-->->>>++>->++>->->>>>++>->++>->->>>>->++>+>->>>>>->++>+>->-->->>>>++>>->->>>>>++>>->->>>>++>->+>->-->->>>->++>>->->>>>->++>>->-->->>>+>->+>->->>>>+>->+>->->>>>++>->>->->->>>+>->>->-->->>>+>->>->->>>>+>->>->->->>>>->>->-->->>>>->>->->>>>>->>->->>>>+>->->->-->->>>>->->->->>>>>->->->++>->->>->>->>+>->->>->>->>>->->>->>->>->->->>->>->>-->->->>->>->>>+++++[>++++++<-]>+[>+++>++>>++>>+++>++>+<<<<<<<<-]>-->>>-->>>>-[>+<---]<[[<]<]<<++[>>[-]--[<+>++++++]+<<<+++>-[>++<<-->-[<++++>-[>--<<++>-]]]<[>>.<<-]>+[>]->[.>]>[<<[<]>>[-]]<<[<+<<<+<<+<<<+<[<]]>>+<<<++]

```

Try it online!

This code reads a list of values and produces output in the pattern `a [> b < c ]> d`, where a, b, c and d stand for a number of '+' or '-' characters.

Except for the first and last 15 numbers, it uses the shortest constants from https://esolangs.org/wiki/Brainfuck\_constants that follow the specified pattern.

```
[
Tape: -2 (end of values), [List of values], 0, 0, "\0 [> \0 < \0 ]> \0 \n" (the spaces are only for better readability.
      Not in the actual string.
      Zeroes are "not printed yet" markers.
      Printed sequences will be prepended by -1.)
List of Values: charCount, class
class: -2 = end of values,
       -1 = (char "+", offset 3),
        0 = (char "-", offset 1),
        1 = (char "-", offset 5),
        2 = (char "+", offset 7)

Ascii:
      ] 93
      [ 91
      > 62
      < 60
      + 43
      - 45
]

[values]
-->>>->>->>->>+>>->>->>->>-->+>->>->>->>->+>->>->>->>>+>->>->>->>->>>>-->+>->->>>>>-->+>->->->>>>->+>->->->>>>-->+>>->>>>>-->+>>->+>>>>-->+>>->->>>>->+>>->>>>>->+>>->+>>>>->+>>->->>>>>+>>->->>-->->->+>->+>>>-->->->+>->+>->>-->->+>+>-->+>>>-->->+>+>-->+>->>-->->>+>->+>->>-->->++>+>-->+>>>-->->++>+>-->+>-->->-->->+>+>->+>->>-->->+>+>->+>->>-->->>+>>+>>>-->->>+>>+>->>-->->++++>+>-->+>->>-->->++>+>->+>>>-->->++>+>->+>->>-->->+>+>>+>>>-->->+>+>>+>->>-->->+++>+>->+>>>-->->+++>+>->+>->->>++>->->+>>-->->>++>->->+>>->>>++>->->+>>->>>++>>>-->+>>>>++>>>-->+>+>>>++>>>-->+>>->->++>>>+>>->->->++>>>+>>-->->->++>>>+>>->>->++>>>+>>>>->++>>>+>>+>>->++>>>+>>-->+>->++>>>+>>+>->>+>>>>>>->>+>>>>>->->>+>>>>>-->->>+>>>>>->>>+>>>>>>>>+>>>>>+>>>+>>>>>-->+>>+>>>>>->+>>+>>>>>>+>>+>>>>>->>++>++>>>>>>>++>++>>>>>+>->->+>>>->+>>->->+>>>->+>->->->+>>>->+>-->->->+>>>->+>->>->+>>>->+>>>->+>>>->+>+>>->+>>>->+>-->+>->+>>>->+>->>->+>>->->+>>>->+>>->->+>+>>->+>>->->+>>->++>+>>>>>->->++>+>>>>>-->->++>+>>>>>->>++>+>>>>>>>++>+>>>>>+>>++>+>>>>>-->+>++>+>>>>>+>++>-->+>>>>>>++>-->+>>>>>->++>-->+>>>>>++>->-->+>>>>>+>->-->+>>>>>>->-->+>>>>>->->-->+>>>>>-->->-->+>>>>>->>-->+>>>>>>>-->+>>>>>+>>-->+>>>>>-->+>-->+>>>>>->+>-->+>>>>>>+>-->+>>>>>+>+>-->+>>>>>++>+>-->+>>>>>+++>+>-->+>>>>>++++>+>-->+>>>>>>++>>+>+>>>>->++>>+>+>>>>++>->>+>+>>>>+>->>+>+>>>>>->>+>+>>>>->->>+>+>>>>-->->>+>+>>>>->>>+>+>>>>>>>+>+>>>>+>>>+>+>>>>-->+>>+>+>>>>->+>>+>+>>>>>+>>+>+>>>>->->++>+>->->>>-->->++>+>->->>>->>++>+>->->>>>>++>+>->->>>+>>++>+>->->>>-->->++>++>+>>>>->>++>++>+>>>>>>++>++>+>>>>->>+>>-->+>+++>+>-->->+>>>+>->+>->>+>>>+>->+>->>+>>-->+>+>+>->->+>>-->+>->+>-->->+>>-->+>->+>->>+>>-->+>->+>+>->+>>>>+>>>->+>>>>+>>->->+>>>>+>>-->->+>>>>+>>->>+>>>>+>>>>+>>>>+>>->>+>>-->->+>>>>+>>-->->+>>+>>+>>-->->+>>-->+>+>>-->->+>>->+>+>>-->->+>>->>+>>>->->+>>>+>>>->->+>+>>+>>>->->+>->>+>>>->+>+>->>+>>++>->->+>>>+>>++>->->+>->>+>>>->+++>+>-->->++>++>->->>>->>++>++>->->>>>>++>++>->->>>->->++>+>+>>>>-->->++>+>+>>>>->>++>+>+>>>>>>++>+>+>>>>+>>++>+>+>>>>++>->>+>->->>>+>->>+>->->>>>->>+>->->>>->->>+>->->>>-->->>+>->->>>->>>+>->->>>>>>+>->->>>+>>>+>->->>>-->+>>+>->->>>->+>>+>->->>>>+>>+>->->>>+>+>>+>->->>>++>+>>+>->->>>++>++>-->+>-->->>>+>++>-->+>-->->>>>++>-->+>-->->>>->++>-->+>-->->>>++>->-->+>-->->>>+>->-->+>-->->>>>->-->+>-->->>>->->-->+>-->->>>-->->-->+>-->->>>->>-->+>-->->>>>>-->+>-->->>>+>>-->+>-->->>>-->+>-->+>-->->>>->+>-->+>-->->>>>+>-->+>-->->>>+>+>-->+>-->->>>++>+>-->+>-->->>>+++>+>-->+>-->->>>>->++>+>-->->>>->->++>+>-->->>>-->->++>+>-->->>>->>++>+>-->->>>>>++>+>-->->>>+>>++>+>-->->>>-->+>++>+>-->->>>->->->+>-->+>->+>-->->->+>-->+>->+>->>->+>-->+>->+>>->->+>-->->->+>->->->+>-->->->+>-->->->+>-->->->+>->>->+>-->->->+>>>->+>-->->->+>+>>->+>-->->->+>-->+>->+>-->->->+>->+>->+>-->->->+>-->->++>++>-->->>>->>++>++>-->->>>++>->>+>-->->>>+>->>+>-->->>>>->>+>-->->>>->->>+>-->->>>-->->>+>-->->>>->>>+>-->->>>>>>+>-->->>>+>>>+>-->->>>-->+>>+>-->->>>->+>>+>-->->>>>->->++>-->->+>>->->->++>-->->+>>-->->->++>-->->+>>->>->++>-->->+>>>>->++>-->->+>>+>>->++>-->->+>>-->+>->++>-->->+>>->->>++>-->->-->+>-->->>++>-->->-->+>->>>++>-->->-->+>->>>++>+>>+>>>>>++>+>>+>>+>>>++>+>>+>>-->->>>+>++>+>->->>>>+>++>+>->-->->>>->++>++>->->>>>->++>++>->-->->>>>++>+>->->>>>>++>+>->->>>>++>++>>->-->->>>++>->++>->->>>>++>->++>->->>>>->++>+>->>>>>->++>+>->-->->>>>++>>->->>>>>++>>->->>>>++>->+>->-->->>>->++>>->->>>>->++>>->-->->>>+>->+>->->>>>+>->+>->->>>>++>->>->->->>>+>->>->-->->>>+>->>->->>>>+>->>->->->>>>->>->-->->>>>->>->->>>>>->>->->>>>+>->->->-->->>>>->->->->>>>>->->->++>->->>->>->>+>->->>->>->>>->->>->>->>->->->>->>->>-->->->>->>->

>>+++++[>++++++<-]>+        31
[>+++>++>>++>>+++>++>+<<<<<<<<-]    93 62 0 62 0 93 62 31
>-->>>-->>>>-[>+<---]       complete string 0 0 91 62 0 60 0 91 62 0 10
<[[<]<]<<                   go to first class cell
++[                         repeat for each value pair
  >>[-]--[<+>++++++]+<      ascii plus
  <<+++                     add offset 3 to value
  >-[                       if not class = "plus 3"
    >++                     change charater to minus
    <<--                    set offset to 1
    >-[                     if not class = "minus 1"
      <++++                 set offset to 5
      >-[                   if not class = "minus 5"
        >--                 set charater to plus
        <<++                set offset to 7
        >-                  delete class value
      ]
    ]
  ]
  <[>>.<<-]                 print char value plus offset times
  >+[>]                     go to next string
  -                         set printed marker
  >[.>]                     print string
  >[                        if not end of chars
    <<[<]                   go to cell next to next class cell
    >>[-]                   empty two cells right (for exit if)
  ]<<[                      else
    <+<<<+<<+<<<+           reset printed markers
    <[<]                    go to exit if cell
  ]
  >>+                       set empty cell = 1 (for scanning over non null cells)
  <<<                       go to class cell
  ++                        repeat if not end of values
]

```

# brainfuck (the easy way), 41 + 32895 = 32936 bytes

```
+[>>++++++++++.+[<++++>-]<-<[>.>+<<-]>>+]

```

Try it online!

```
+[              start loop (loop until overflow)
  >>            go to newline position
  ++++++++++.   print newline
  +[<++++>-]<-  store 43 (plus)
  <[            for each count
    >.          print plus
    >+          increment next count
    <<-         decrement current count
  ]
  >>+           increment next count
]

```
> 3 votes

# Answer
# Ruby 23 + 32895 = 32918 bytes

```
256.times{|n|puts ?+*n}

```

As a baseline. This is the simplest solution I can think of.
> 2 votes

# Answer
## Unofficial Keg 16 + 32895 = 32911 bytes

A baseline solution for a golfing language. This is the simplest I can think of.

```
ÿï((:|\+$;)_\
')

```

Try it online!
> 2 votes

# Answer
# Retina 0.8.2, 28 + 16640 = 16668 bytes

```

127$*+128$*-
\+
¶$`+
-
¶$'-

```

Try it online! Includes output for `0`. Just outputs using `+`s up to 127 and `-`s up to 255.
> 1 votes

# Answer
# Scala, 95 + 16639 = 16734 bytes

```
object M extends App{(1 to 127).map(x=>println("+"*x));(0 to 127).map(x=>println("-"*(128-x)))}

```

Try it online!

A simple answer which obviously is not going to win. Uses only the fact that the `-` operator (decreasing a byte) wraps back to 255.
> 1 votes

# Answer
# 05AB1E, score: 4848 (1219 bytes source code + 3629 bytes output)

```
'+14L×»Â'+'-:•тômG‚ΣP;e3₃ìèÕwƵÜè-½;¨Z±µΛé±V™NkKJžšë₅ušΘ(M₄+Ü§‘мoÕθÚzÇYï#J×¢θýει™₃tQØËв¿U®GƵ´GZ’¯ε¨jjØÛλÄ₅X∍µxθÆvËjS¹∊f˜«VÐZ<ÇĆ’Š2&ØÍäßÍĆlΓV₆ëßê©Œ‡ÛiyĆ=*÷Í´¢‹j,3½íµ'ž4‘û29ôãζм§x…1P|ÛéΣ=~çš5Œ±€Ô“q òǝ?ó¬Æí5¢G‘°êóÿв4LFÍK&zζb2Ó∍æïι8₃4XƵÜÙôt₁‘,Ö…6₅ÞαÇø†c÷Ûλ9…F;ĆA¬iмéλ8ä¶×ƶYΔè¡aû
v=M„ûñ]C₅Õ¶Þ*Ú`Úˆ/₃UιΩW¾eTεvˆ£nYõ¶S¼ÿ{õN9Ω¨£1w‚Ï”Xd;¹OýŒéDнĀvÌ–d=±ΛΣÃÊîD—GR>~ºD‹K¥‘l×yz.éFE1Í©ØM/ƒœOαU‘KΓO‰∍Aм‚œ2нƶþøÌ×¼āHgΩC'Λê¡-ß…Ì¾Ā–м–¿<₂δ¡áтgö¬Í~θFíнā‹°ü8[À(xï¸.›*W©¹º₅ÇмδçΛλÉFÕL4†EćÛ´ǝ{тÀ¯†ª™ŽćÉuè¬ƵÀSìFÙη¶1È¸Ö›GÜlRv˜jy5mfè∞_åEηŠyo‡xÐ/™¥òÜ#Áx#м6r&₁cÿXÛ¬Æ„ÌƵ₅∊Ð±γ²Θj∞;6o·¼ýŠΩÚò›c[>ö₅¥=—ªÃ±¿ecSBÐ6Ê!ú¢E¡âìþßƒ¿;Ò;„Xoƶ*∍Σǝñ"Tµ†8s®βµ4ìA|«÷γt³+<B¤špTp¸ï7Ëo[>–îiTôóζª‚?É8zн²ìC1ãl6+ƶå4sÐŒÃšb(°·8ˆ´ˆŸ²ÚÌY3ŸËÃ®ÿ‘àUāçh9im„ÝĆm3ŠC×η“åX¨₄|ëPô3O<6Mþ'Ì-s{e`ζQΔ¹œP@l%¥‹èδcsÎcΘÂþ®i₅∞ð¡@`¸¿…BÎN2н>g;ΛSníÐ^Rαθ₆ΣÕ3¹ÐÔCfrQ¦7¨gfŒ|v||þÚÜvz≠pá»‡T˜ǝ=ß·„®¡xи™#?†-Aʒ2åβ₃A¬Ão6ºтõ}Ë.&QηÕ~Δ4€@-5î^aÌ¬.»Èõ4áL¾ò¥n
¶p›éŽžgǝSZγāmεålz₅°dβÂ~λà€Ê%zmŠиˆRη≠éwüǝΛζƵмƶdζ`SÖ₅\≠³äŸj!"(†Üćí“ŠxVöÇe#‡PÏÉ‡"xð®6ÊεGиe"NÊ›i.k…’Ú8:ǝ/₂ÌÜkãŽo™Áā‚ζΩ«мÁp=}ÂýõλиëÆζиîSÖt¶‚wĀθºd“
₆ŽsLвQ”ÖÜvGõƶiò{÷ÀPy/‹θÑè}¿Á5º˜¯sëØSËƶK_ÍyX∊3Øå4IOθ I+∊ÌñÙçakÞŸŒʒζ¤±,mεjæ‰O%<ÅtƒVöV=³ÇƶƒC¬‰xðÈ¬M4Ïóä)∍Êfa§õØÂ,“X¾₆₄Ö¦ÈJµÿmÈ¾Î∍=¡YнŸV!¨J£ü|&¢cUg4e±6w™¼“fÊÙ ,Ž|šP·ùèd}ãŠÅ#GγhYÇN´¼ÁÌMGʒ§Æ1¸‚Δ:j7ΩƵAqá¢<äò´Θ•“-+>][<
“ÅвJs»

```

Output is a port of *@Neil*'s Charcoal answer, so make sure to upvote him as well!

Try it online.

**Explanation:**

```
'+                      '# Push a "+"
  14L                    # Push a list in the range [1,14]
     ×                   # Repeat the "+" that many times as string: ["+","++","+++",...]
      »                  # Join these strings by newlines
       Â                 # Bifurcate it (short for Duplicate & Reverse copy)
        '+'-:            # Replace all "+" for "-"
•тôm...ò´Θ•              # Push compressed integer 18302226724133383998250107335646038608225046109581810887431446835557987256955354954509163336111304735021044106950262344427892947550841899099611054599885158084492762836812161427050275372983896356189873217422270707048679161884382784973706990123491668808316983431947218815813441209357230471947480445527653281307616982417034289994948061000591427114479102114229222423495882782326672492922269629953210111953959859902281658658439835047182218017657439552630082372181376525413759195763958434475193943488791777228373958162363214252781530693967200164833437881609482421594458966138936433283311419810119896020066082377462298326514652481546557215787238749539873039910952003326954299252586309028025200870623285261199142261807190771369911425142504345271105103035478661301795311828767848235694787283635190364512722037791815037475799545052058894119573664059402985074146226606245848663046901585891882552845134633210352731812274795773552227786140415336764040421001184646630833787917147474644077938952053956874031774587527717793206158934471919975714697099518810712871948398923739276321843455690477328633199064849928974478179435369018512187592263559949835435473650276637191671401061097340919482725489354844550472281209666291367830643727358624135371626379451084552903536762775083445643853806852513122856150361979701049267928548063465967555886420646898485890108420374549485423234679327438138302730692296669063696581268627535131608200283731275951916433249161017999011290215932205767570177905442947203826039265793694687731078121685736352831955773450680945121984143563963149079990880719573067270197057276219243821370885160589340870891346257233778661271435191351926058080186177296974642815621539128350975752011448032262905976766027084285390087966682234081285502231618383962136055937741758125210487103109250885525370548106186539295203084216890820183575639032509902729248016346072449636148699098049659529168757116706057794418245039559549604674043961198447420311513558044229534569679723496972989178091506175996419296780639212192856671882116470677803387276814324094247508763467887301684211112080372036284371596072213153957411329532202432808677726223798116216330275138697515009114689489577370759238857602332613821627667530873656034962827810927061440822808985980383150080767015247752949877604372029666921293343149038246728649404223795601960991061986482063744094221616603849190547637439116347239768975065217383194655478092271791087679802480625740835053103772632489195507735140119501008503485917456615266596210333924964188989678201446160111091052524780358620148464886929989973412559470628329156848340802659185674541202787279386158230228148429451357621709967247567009904339076971643378255946241011579618610095231079053137553024558887196808709177094386352264708730475553352082713138948975317023830903305435434148828341201637230241697870602236452176330225025183518037443992277303117971849493548326433875
           "-+>][<\n"    # Push string "-+>][<\n"
                     Åв  # Convert the integer with this string as custom base
                       J # Join all characters together to a single string
s                        # Swap so the triangle of "-" we created it as the top of the stack
 »                       # Join the strings on the stack by newlines
                         # (and output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers*) to understand why `•тôm...ò´Θ•` is `183...875`.
> 1 votes

# Answer
# Rust \+ `-O`, ~~618~~ 576 + 3953 = ~~4571~~ 4529 bytes

`-O` to turn on optimizations, otherwise TIO times out because it's too slow. If you're using cargo, use `--release` instead.

```
||{let r=|s:&str,n:i64|s.repeat(n as usize);let f=|n:i64|if n<0{r("-",-n)}else{r("+",n)};let w=|n:i64|n as u8 as i64;print!("{}",(0..256).flat_map(|n|(0..9).flat_map(|a|(-9..=a).map(move|b|(a,b))).flat_map(|x|(-9..9).map(move|c|(x,c))).flat_map(|x|(-9..10).map(move|d|(x,d))).filter_map(|(((a,b),c),d)|match(0..256).scan(a,|s,_|if *s>0{*s=w(*s+d);Some(1)}else{None}).sum(){256=>None,r if w(r*b+c)==n=>Some(format!("{}[>{}<{}]{}{}",f(a),f(b),f(d),if c!=0{">"}else{""},f(c))),_=>None}).chain(vec![r("+",n),r("-",256-n)]).min_by_key(|s|s.len())).fold(format!(""),|a,b|a+&b+"
"))}

```

Try it online!

This generates programs in the shortest of the following 3 forms:

* `+++...`
* `---...` (using underflow)
* `a[>b<c]d`, where a, b, c, and d are some number of '+' or '-' characters

Full explanation:

```
// Closure
|| {
    // Repeats a string (shorthand)
    let r = |s: &str, n: i64| s.repeat(n as usize);
    // Formats a constant as a sequence of '+' or '-' characters (depending on sign)
    let f = |n: i64| if n < 0 { r("-", -n) } else { r("+", n) };
    // Wraps an i64 around a u8 cell
    let w = |n: i64| n as u8 as i64;
    // Print the solution
    print!("{}",
        // For rows [0, 255]
        (0..256)
            // ... map each row to its solution
            // For a in [0, 8]
            .flat_map(|n| (0..9)
                // For b in [-9, a] (flattened to `(a, b)`)
                .flat_map(|a| (-9..=a).map(move |b| (a, b)))
                // For c in [-9, 8] (flattened to `((a, b), c)`)
                .flat_map(|x| (-9..9).map(move |c| (x, c)))
                // For d in [-9, 9] (flattened to `(((a, b), c), d)`)
                .flat_map(|x| (-9..10).map(move |d| (x, d)))
                // Calculate result of `a[>b<d]c`
                .filter_map(|(((a, b), c), d)| {
                    // Loop up to 256 times to calculate the number of times X will run in `a[>X<d]`
                    match (0..256)
                        .scan(a, |s, _| {
                            if *s > 0 {
                                *s = w(*s + d);
                                Some(1)
                            } else {
                                None
                            }
                        })
                        .sum()
                    {
                        // Assume infinite loop
                        256 => None,
                        // Finite loop, ends in the value we want, now format the values
                        r if w(r * b + c) == n => Some(format!("{}[>{}<{}]{}{}", f(a), f(b), f(d), if c != 0 { ">" } else { "" }, f(c))),
                        // Finite loop, doesn't end in what we want
                        _ => None,
                    }
                })
                // Append the trivial cases of all '+' or '-' characters
                .chain(vec![r("+", n), r("-", 256 - n)])
                // Find the shortest solution
                .min_by_key(|s| s.len())
            )
            // Join each row
            .fold(format!(""), |a, b| a + &b + "
")
    )
}

```

Decompressing a solution would definitely be shorter, but this was more fun in my opinion :)
> 1 votes

# Answer
# GolfScript, 296 + 3628 = 3924 bytes

```
12.?:&{{}if}:i{&6base:c[0:x:^:h]25:e*:|"(":a")":b{["x(:x|,,?):e".a/b*"|x=(256%|x<\\|x)>++:|".a/b*"{1{c^):^=.4={;)}{5={b}i}if.c,,^)?1+:e*}do"."^)c,-"\"b"/a*+"!{e):e}i^(:^}i"+"|x="@b/a*"b"/b*"}i"++]c^==~];^):^c,=!6.?,h):h?)e*:e*}do|$)\{+}*!*.e*{c':c'@+~}i&(:&}do];255,{n'c'@)+~{'<>-+[]'1/\=}/}/"":n

```

Try it online!

The extra byte in the output is a newline for the code for 0, removing it requires more than one byte.

This program passes through 8 916 100 448 256 BF codes, tests if it produces only one number and stores the code. In the end the shortest code for each number is printed. This is not effitient at all, it would take millions of years to end, the estimated number of bytes in the solution assumes the shortest codes are all listed in this esolang page. This doesn't reach the memory limit or any other errors I know, it is just very slow.

```
12.?:&          # Assign 12^12 = 8916100448256 to &, this represents the current BF code
{{}if}:i        # This will be used to go from {code}{}if to {code}i
{  ...  }do     # Main loop, will be explained later
];              # Clean the stack
255,{  ...  }/  # Go through every number
"":n            # This removes the automatic newline that is printed

```

What is inside the `255,{ ... }/`:

```
n                      # Newline
 'c'@+                 # For the N-th number push 'cN'
      ~                # Execute the string, this will push the value stored in the variable, it will be an array with the shortest code for N
       {'<>-+[]'1/\=}/ # Translate the array to a BF code

```

Main loop:

In the main loop there is a BF interpreter that can avoid errors. There are 3 ways something can go wrong:

1 It doesn't halt. This can be avoided by putting an operation limit. Here the limit is 14889 for the numbers 78 and 178, this means that if the code doesn't halt in 14889 operations, it is not one of the optimal codes.

2 Unpaired `[ ]`. We test if the instruction pointer left the code while searching for the pair. If it isn't necessary to look for the pair (Eg `>>]+-`), it means that that instruction is not necessary and the code will be replaced by a better one later.

3 The data pointer leaves the tape. We test if it left the tape using the same strategy used above. The tape here is only 25 bytes long, if the code needs more, it means it isn't optimal. The numbers 78 and 178 need 24 cells.

This interpreter doesn't have the `,` and `.` operations, so every BF code can be represented by a base 6 number. The problem is that a number can't start with 0, but here it isn't a problem because 0 represents `<`, which doesn't do anything at the start.

```
&6base:c                              # Convert & to base 6 and store the resulting array in c.
        [0:x:^:h]                     # Push [0] and assign 0 to x, ^ and h. x= data pointer  ^= instruction pointer  h= operation counter
                 25:e                 # Assign 25 to e, this will be the error variable, if it is 0 something went wrong
                     *:|              # Multiply [0] and 25 to get the tape called |
                        "(":a")":b    # Assign "(" to a and ")" to b
                                  {[  # Start a loop and an array

```

In this array we will have the 6 functions written as strings for easier manipulation:

```
op      string
0 <     x(:x|,,?):e
        x(:x                   # Decrement x
            |,,?):e            # Test if the result is within the tape

1 >     x):x|,,?):e            # Same thing as before but with ")" instead of "("

2 -     |x=(256%|x<\\|x)>++:|
        |x=                    # Get the value from the tape
           (256%               # Decrement mod 256
                |x<\\|x)>++:|  # Replace the old value in the array, the \\ is a \ but inside a string

3 +     |x=)256%|x<\\|x)>++:|  # Same thing as before but with ")" instead of "("

4 [     ^)c,-{1{c^):^=.4={;)}{5={(}i}if.c,,^)?1+:e*}do!{e):e}i^(:^}i
        ^)c,-{                                                    }i  # If it isn't the last byte of the code
              1{                       .c,,^)?1+:e*}do                # While the pair has not been found and the next byte to be tested is within the code
                c^):^=                                                # Get next byte
                      .4=            if                               # Is it a [ ?
                         {;)}                                         # Increment the counter
                             {5={(}i}                                 # Decrement the counter if it is a ]
                                                      !{e):e}i        # If the code ends with ] it will be counted as an error and this part solves the problem
                                                              ^(:^    # Move the instruction pointer to the left, later it will be moved to the right and the ] will be read

5 ]     |x={1{c^(:^=.4={;(}{5={)}i}if.c,,^(?1+:e*}do}i
        |x={                                        }i                # If the current cell is not 0
            1{c^(:^=.4={;(}{5={)}i}if.c,,^(?1+:e*}do                  # Same thing as before but with ( and ) swapped

```

`[` always jumps to the `]` and there it decides if the things inside should be executed.

This array is very repetitive, so we replace `"x):x|,,?):e"` by `.a/b*`, this copies the code for `<` and replaces the `(` by `)`. The code for `+` is also replaced by `.a/b*`, but the code for `]` is a bit more complex. The code for `[` and `]` will be replaced by:

```
"{1{c^):^=.4={;)}{5={b}i}if.c,,^)?1+:e*}do"."^)c,-"\"b"/a*+"!{e):e}i^(:^}i"+"|x="@b/a*"b"/b*"}i"++

"{1{c^):^=.4={;)}{5={b}i}if.c,,^)?1+:e*}do"             # Repeated part

."^)c,-"\                                               # Make a copy of it and push ^)c,- under that long string
         "b"/a*+                                        # Replace the b by ( and concatenate the result with the ^)c,-
                "!{e):e}i^(:^}i"+                       # Add this to the end of the string
                                 "|x="@                 # Push |x= and get that original string
                                       b/a*"b"/b*       # Replace the ) by ( and the b by )
                                                 "}i"++ # Push }i and concatenate the 3 parts

```

Now comes the part that executes these functions, remember that this array was created inside the loop, this means it will be recreated every time it reads a byte from the code.

```
]                                   # End the array
 c^=                                # Get current instruction
    =~                              # Get the function for it and execute it
      ];                            # Clean the stack, this replaces the ; that would have to be in every function
        ^):^                        # Go to next instruction
            c,=!                    # Is it NOT the last instruction?
                6.?,h):h?)          # Increment h and test if it is within the operation limit. It actually uses 6^6=46656 instead of 14889 to save 2 bytes.
                          e*:e      # Updates e
                              *}do  # Repeats everything if there were no errors

```

Now we just have to test if the output is valid and store it if it is.

```
|$                                  # Sort the tape
  )                                 # Separate the last number
   \{+}*                            # Add all other numbers in the array
        !                           # Is the sum 0?
         *                          # This will be the only non-zero cell or 0 if the output is invalid
          .e*                       # Change it to 0 if there was an error
             {        }i            # If it isn't 0 it is the code for some number, let this number be N
              c                     # Push the code
               ':c'@+~              # Store it in the variable cN
                        &(:&}do     # Go to the next code and repeat untill it gets to 0

```

The codes are tested in decreasing order, that way the shortest solutions will automatically replace the longer ones. The longest code is number 6774727080140 and that's why we started at such a big number.

Here are some versions of the code using other constants so we can see the output (only the found codes are outputted):

Starting at 216, this tests every 3 byte code.

From 6774727080145 to 6774727080135, includes the solution for 117.

30 codes starting at a random number
> 0 votes

# Answer
# Python 3, 80 + 9839 = 9919 bytes

```
for n in range(1,256):m=int(n**.5);s='+'*m;print(f">{s}[<{s}>-]<{'+'*(n-m**2)}")

```

Try it online!

Expanded:

```
for n in range(1, 256):
    m = int(n ** 0.5);
    s = '+' * m;
    print(f">{s}[<{s}>-]<{'+'*(n - m**2)}")

```

Process:

* try to do a square number amount of increments
* add the remaining +'s to the end

The program loops for 1 - 255, not including 0 because while that saves 2 bytes in the input, it adds \>2 bytes to the output. The brainfuck memory is laid out so that we have \[num, square\_counter\]. And it puts m +'s in square\_counter, then m +'s every time that decrements up to 0. Then we just add n - m^2 more pluses at the end.
> 0 votes

---
Tags: code-challenge, brainfuck, code-generation
---


# Question
Title: (Σ*)² ⟲ Σ* (aka Round-Trip a String Pair)
This is a challenge I thought of recently which I think is not hard but allows for a wide range of possible solutions. Seems like a perfect fit for the creativity of PPCG users :)

## Your Task

Define two functions which together form a lossless round-trip `String × String → String → String × String`.

More specifically, define two functions `combine` and `separate` with repsective types `String × String → String` and `String → String × String` such that `separate ∘ combine = id`.

Even more specifically, define two functions (or methods/procedures/etc), which I will refer to as `combine` and `separate`, and which exhibit the following characteristics:

* When invoked with a single string, `separate` produces two strings as results. (You may use any reasonable string type. Most languages don't canonically allow producing multiple values, so feel free to to do something equivalent, such as returning a 2-tuple or modifying two global variables.)
* When invoked with two strings, `combine` produces a single string as result. (You may accept input to `separate` in the same form that `combine` produces, or any other reasonable form.)
* For any two strings `a` and `b`, `separate(combine(a, b))` must result in two strings which are (structurally) equivalent to `a` and `b`.
* The above bullets are the *only* restrictions on `combine` and `separate`. So, for instance, `combine ∘ separate` need not be `id`, and `separate` can even be a partial function, if you like.

(Defer to the final and more-verbose description if there are any ambiguities between the three)

## Intent

My goal with this challenge is to inspire creative and interesting solutions. As such, in order to avoid priming/suggesting your thinking about how to solve this problem, I will not be providing test cases, and I **strongly** suggest that you do not look at the existing answers until you submit your own.

## Winning Criteria

This challenge is a ; the answer with the highest score at noon on April 5th, UTC, is the winner.

Guidelines for voters, included to be a valid , are as follows:

* Strongly prefer answers which you do not immediately comprehend, are not obviously correct, and/or surprise you
* Prefer answers which go beyond strings, i.e., those which make use of more than the problem statement did (functions, strings, pairs)
* Avoid answers which are similar to your own solution(s)
* Avoid answers which boil down to language builtins

---

Have fun!

# Answer
I know this is extra credit, but your problem got me thinking a lot about this and what interested me the most was not just `separate` being the left inverse of `combine`, but having them be true inverses of each other. This ends up with us defining a bijection from `String -> String x String`. The path I took was as follows

* Define a bijection from `String -> N`
* Define a bijection from `N -> N x N`
* Combine them to get the functions we need

### String -\> N

Let `r` be the size of the character set you're working with and give each character a unique value from 1 to `r`, say `f(c) = n`. Going from right to left and indexing starting from zero, create the number `f(s[0])r^0 + f(s[1])r^1 + f(s[2])r^2 ... f(s[length(s)])r^(length(s))`. The lowest number you can get this way is 1, so we let the empty string equal 0.

### N -\> N x N

Take `n` in any base you like. Separate even digits into one part of the tuple and the odd digits into the other to make a pair of numbers. E.g. `12345 -> (24, 135)`. To work your way back, combine the numbers in the opposite way, inserting extra zeros as necessary.

### Putting it all together

# Haskell

```
module Main where

import Data.Function ((&))
-- tio is saying this isn't correct for some reason so gotta define it manually
-- import Data.Functor ((<&>))

main :: IO ()
main = do
  putStrLn $ show $ separate "Hello, world!"
  putStrLn $ combine ("Hello, world!", "")
  putStrLn $ show $ separate $ combine ("Hello, world!", "")
  putStrLn $ combine $ separate "Hello, world!"

separate :: String -> (String, String)
separate str =
  str
  <&> toInt
  & fromNZ
  & split
  & tmap toNZ
  & tmap (map fromInt)

combine :: (String, String) -> String
combine strs =
  strs
  & tmap (map toInt)
  & tmap fromNZ
  & join
  & toNZ
  <&> fromInt

base :: Int
base = 95

toInt :: Char -> Int
toInt c = fromEnum c - 31

fromInt :: Int -> Char
fromInt i = toEnum $ i + 31

strip :: [Int] -> [Int]
strip is = case is of
  0 : i : tail -> strip $ i : tail
  _ -> is

split :: [Int] -> ([Int], [Int])
split =
  tmap strip . fst . foldr
    (\a ((acc1, acc0), i) ->
      (if mod i 2 == 0 then
        (acc1, a : acc0)
      else
        (a : acc1, acc0)
      , i + 1
      )
    )
    (([], []), 0)

join :: ([Int], [Int]) -> [Int]
join (l1, l2)= strip $ reverse $ go [] (reverse l1, reverse l2)
  where
    go :: [Int] -> ([Int], [Int]) -> [Int]
    go acc (l1', l2') = case (l1', l2') of
      (head1 : tail1, head2 : tail2) -> head2 : head1 : go acc (tail1, tail2)
      ([], head : tail) -> head : 0 : go acc ([], tail)
      (head : tail, []) -> 0 : head : go acc (tail, [])
      ([], []) ->  acc

tmap :: (a -> b) -> (a, a) -> (b, b)
tmap f (a1, a2) = (f a1, f a2)

fromNZ :: [Int] -> [Int]
fromNZ is =
  if is == [] then [0]
  else let
    (result, finalCarry) =
      foldr
        (\i' (acc, carry) ->
          let
            i =
              if carry then i' + 1
              else i'
          in
            if i >= base then (i - base : acc, True)
            else (i : acc, False)
        )
        ([], False)
        is
  in
    if finalCarry then 1 : result
    else result

toNZ :: [Int] -> [Int]
toNZ is =
  if is == [0] then []
  else let
    (result, finalUncarry) =
      foldr
        (\i' (acc, uncarry) ->
          let
            i =
              if uncarry then i' - 1
              else i'
          in
            if i <= 0 then (i + base : acc, True)
            else (i : acc, False)
        )
        ([], False)
        is
  in
    if finalUncarry then
      case result of
        a : tail ->
          if a == base then tail
          else result
        _ -> result
    else result

m <&> f = f <$> m
infixl 1 <&>

```

Try it online!
> 7 votes

# Answer
# Charcoal

Simply lists the code points in both strings. Within each string, code points are delimited with commas, and the two strings's code points are separated with a semicolon. The only gotcha is to ensure that empty strings decode to empty strings.

## Combine

```
⪫Ｅ²⪫ＥＳ℅λ,¦;

```

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

## Separate

```
Ｅ⪪Ｓ;∧ι⭆⪪ι,℅Ｉλ

```

Try it online! Link is to verbose version of code.
> 3 votes

# Answer
# Charcoal

Works by prefixing each character of the first string with a comma, suffixing each character of the second string with a comma, and then joining the strings with a semicolon. This simplifies decoding as there are an equal number of commas and original characters. There is a slight Charcoal gotcha in that it can't chop a zero-length string, so to obtains the first string the decoder chops the original string at the semicolon before stripping the commas (still one byte shorter than slicing though), while for the second string it can strip the commas first and then slice from where the semicolon used to be.

## Combine

```
⪫Ｅ²⭆Ｓ⎇ι⁺λ,⁺,λ;

```

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

## Separate

```
≔⌕Φθ¬﹪κ²;η⟦Φ…θ⊗η﹪κ²✂Φθ﹪κ²η

```

Try it online! Link is to verbose version of code.
> 2 votes

# Answer
# JavaScript

```
const obfuscate = str => [...str].map(e=>e.charCodeAt(0).toString(36) + '?').join``;
const combine = (first, second) => obfuscate(first) + ' ' + obfuscate(second);
const separate = string => string.split(' ').map(x =>x.split('?').filter(b=>b).map(el => String.fromCharCode(parseInt(el, 36))).join``);
```

> In this case, `separate` is a partial function because it is only defined on specially formatted strings generated by `combine`. The `obfuscate` helper function turns the input string into an array of strings composed of the base-36 representation of the current character codepoint, plus a question mark. The array is then joined and returned. Then, `combine` returns the obfuscation of the first string, a space, then an obfuscation of a second string. `separate` undoes `obfuscate` on both strings and returns the array, in essence. Upon reading the answers, I found out that I sorta ported @Neil's answer with the difference being that I used a base-36 representation.
> 2 votes

# Answer
Can't let @Mason have it for free (edit 1: also @Neil posted as I write this), so I'm dropping in with answer number 4 and 5 (edit 2: goddamn someone posted another answer): the *python convertors*.

# Answer One: the easy version

## (string conversion using split())

```
import math
def combine(stringA, stringB):
  stringC = stringA + "\n" + stringB
  len1 = len(stringC)
  stringD = stringC * len1
  return stringD
def seperate(stringE):
  len2 = math.isqrt(len(stringE))
  stringF = stringE[0:len2]
  stringG, stringH = stringF.split("*", 2)
  return stringG, stringH

```

This functions takes two strings, combines them with an asterisk and then multiplies them by their combined length (plus the asterisk). To decode, it takes the square root of the length, splits ton the asterisk, and returns the strings (tested).

Now for the *hard* version.

# Answer Two: the actually hard version

## (hex conversion)

```
def combine2(stringI, stringJ):
  stringK = stringI + "\n" + stringJ
  integerA = stringK.encode().hex()
  integerB = int(integerA, 16)
  return integerB
def seperate2(integerC):
  integerD = (int(integerC))
  integerE = hex(integerD)
  stringL = str(integerE)
  stringM = stringL[2:]
  stringN = bytes.fromhex(stringM).decode('ascii')
  stringO, stringP = stringN.split(":")
  return stringO, stringP

```

Three years later and I've actually done it: this code can first convert a string to hex, return that, then take that hex string (note, leave the 0x in or the first character will be removed) and convert it to the string that you originally had (again, ***painfully*** tested). (Edit 3: now you can't break it - newlines can't appear in input)
> 2 votes

---
Tags: string, popularity-contest
---