text:
Is this a truncated triangular number?
Related OEIS sequence: A008867
Truncated triangular number
A common property of triangular numbers is that they can be arranged in a triangle. For instance, take 21 and arrange into a triangle of os:

     o
    o o
   o o o
  o o o o
 o o o o o
o o o o o o

Let's define a "truncation:" cutting triangles of the same size from each corner. One way to truncate 21 is as follows:

     .
    . .
   o o o
  o o o o
 . o o o .
. . o o . .

(The triangles of . are cut from the original).
There are 12 os remaining, so 12 is a truncated triangle number.
Task
Your job is to write a program or a function (or equivalent) that takes an integer and returns (or use any of the standard output methods) whether a number is a truncated triangle number.
Rules

No standard loopholes.
The input is a non-negative integer.
A cut cannot have a side length exceeding the half of that of the original triangle (i.e. cuts cannot overlap)
A cut can have side length zero.

Test cases
Truthy:
0
1
3
6
7
10
12
15
18
19

Falsy:
2
4
5
8
9
11
13
14
16
17
20

Test cases for all integers up to 50: TIO Link
This is code-golf, so submissions with shortest byte counts in each language win!

Are we to output truthy and falsy outputs or is two consistent values ok?

@WheatWizard two consistent values are acceptable.

However much the truncations overlap, the result is equivalent to a smaller triangle with smaller truncations (if truncations can have side length 0).

Haskell, 46 45 bytes
f n|t<-scanl(+)0[1..n]=or[x-3*y==n|x<-t,y<-t]

Try it online!

Haskell, 46 bytes
f n=or[mod(gcd(p^n)(4*n-1)-5)12<3|p<-[1..4*n]]

Try it online!
Having thrown a bunch of number theory at the problem (thanks @flawr), I found this characterization:

n is a truncated triangular number exactly if in the prime factorization of 4n-1, any prime of the form 5 mod 12 or 7 mod 12 appears an even number of times.

This means, for instance, that 4n-1 may not be divisible by 5 unless it's further divisible by 52=25 and the total number of 5 factors is even.
Haskell doesn't have a factorization-built-in, but we can improvise. If we work with factorizations into primes powers like 12=3*4, we can use the equivalent statement:

n is a truncated triangular number exactly if the factorization of 4n-1 into prime powers has no terms of form 5 mod 12 or 7 mod 12.

We can extract the power of a prime p appearing in k as gcd(p^k)k. We then check that the result r is not 5 or 7 modulo 12 as mod(r-5)12>2. Note that r is odd. We also check composites as p, lacking a way to tell them from primes, but the check will pass as long as its factors do.
Finally, negating >2 to <3 and switching True/False in output saves a byte by letting us use or instead of and.

A related characterization is that the divisors of 4n-1 taken modulo 12 have more total 1's and 11's than 5's and 7's.
53 bytes
f n=sum[abs(mod k 12-6)-3|k<-[1..4*n],mod(4*n)k==1]<0

Try it online!

Really nice explanation!

Python 2, 52 bytes
f=lambda n,b=1:b>n+1or(8*n-2+3*b*b)**.5%1>0<f(n,b+1)

Try it online!
Outputs True/False flipped. Uses this characterization:

n is a truncated triangular number exactly if 8n-2 has form a2-3b2 for some integers a,b.

We check whether any 8*n-2+3*b*b is a perfect square for any b from 1 to n+1. We avoid b=0 because it gives an error for a square root of a negative when n==0, but this can't hurt because only odd b can work.
Done non-recursively:
Python 2, 53 bytes
lambda n:0in[(8*n-2+3*b*b)**.5%1for b in range(~n,0)]

Try it online!

Are recursive and non-recursive solutions usually so competitive with each other in python?

@boboquack Usually the recursive solution wins by a few bytes over range. Here it's close because  b>n+1 is a lengthy base case and 0in is short.

Jelly, 10 bytes
0r+\ð_÷3f⁸

A monadic link accepting an integer and returning a truthy value (a non empty list) or a falsey value (an empty list).
Try it online! (footer performs Python representation to show the [0] results as they are)
...or see a test-suite (runs for 0 to 20 inclusive)
How?
Given N, forms the first N triangle numbers, subtracts N from each, divides each result by 3 and keeps any results that are one of the first N triangle numbers.
0r+\ð_÷3f⁸ - Link: integer, N             e.g. 7
0r         - zero inclusive range N            [    0, 1, 2,   3,    4, 5,   6,   7]
  +\       - cumulative reduce with addition   [    0, 1, 3,   6,   10,15,  21,  28]
    ð      - start a new dyadic link with that, t, on the left and N on the right
     _     - t subtract N (vectorises)         [   -7,-6,-3,  -1,    3, 8,  14,  21]
      ÷3   - divide by three (vectorises)     [-2.33,-2,-1.33,-0.33,1,2.67,4.67, 7]
         ⁸ - chain's left argument, t          [    0, 1, 3,   6,   10,15,  21,  28]
        f  - filter keep                       [                     1             ]
                                               - a non-empty list, so truthy

R, 45 43 bytes
-2 bytes thanks to Vlo
(n=scan())%in%outer(T<-cumsum(0:n),3*T,"-")

Try it online!
I'm fairly sure we only need to check the first n triangular numbers for this; brute force checks if n is in the pairwise differences of the triangular numbers and their triples.

scan() n<-scan();n%in%outer(T<-cumsum(0:n),3*T,"-")

@Vlo facepalm I got into the habit of using functions everywhere...

And I just got into the habit of using <- assignment instead of (n=scan())...tsk tsk

Pyt, 10 bytes
Đř△Đ3*ɐ-Ƒ∈

Try it online!
Explanation:
        Implicit input
Đ       Duplicate input
ř       Push [1,2,...,input]
△       For each element k in the array, get the kth triangle number
Đ       Duplicate the top of the stack
3*      Multiply by 3
ɐ       ɐ - All possible:
 -                       subtractions between elements of the two arrays
Ƒ       Flatten the nested array
∈       Is the input in the array

You beat me too it, +1 GG

@tfbninja I wish I had a nicer explanation for what ɐ- does

added, you can rollback if you want though

Haskell, 48 bytes
f a|u<-[0..a]=or[x^2+x-3*(y^2+y)==2*a|x<-u,y<-u]

Try it online!

Looks like your check is overlooking a==1.

@xnor I see why.  It has been fixed now.

J, 22 bytes
e.[:,@(-/3*])2![:i.2+]

Try it online!
Straightforward and somewhat-poorly-golfed approach.
Explanation
e.[:,@(-/3*])2![:i.2+]
             2![:i.2+]  Range of triangular numbers up to N
      (-/3*])           All possible subtractions of 3T from T
                        where T is triangular up to the Nth triangular number
    ,@                  Flattened into a single list
e.                      Is N in the list?

e.2,@(!-/3*!)[:i.2+]

e.2,@(!-/3*!)1+i.,] maybe

MATL, 12 bytes
tQ:qYst!3*-m

Outputs 1 for truthy, 0 for falsy.
Try it online! Or verify all test cases.
How it works, with example
Consider input 6
t      % Implicit input. Duplicate
       % STACK: 6, 6
Q:q    % Increase, range, decrease element-wise. Gives [0 1 ... n]
       % STACK: 6, [0 1 ... 6]
Ys     % Cumulative sum
       % STACK: 6, [0 1 3 6 10 15]
t!     % Duplicate, transpose
       % STACK: 6, [0 1 3 6 10 15], [0;
                                     1;
                                     3;
                                     6;
                                     10;
                                     15]
3*     % Times 3, element-wise
       % STACK: 6, [0 1 3 6 10 15 21 28 36 45 55], [0;
                                                    3;
                                                    9;
                                                    18;
                                                    30;
                                                    45]
-      % Subtract, element-wise with broadcast
       % STACK: 6, [  0   1   3   6  10  15  21;
                     -3  -2   0   3   7  12  18;
                     -9  -8  -6  -3   1   6  12;
                    -18 -17 -15 -12  -8  -3   3;
                    -30 -29 -27 -24 -20 -15  -9;
                    -45 -44 -42 -39 -35 -30 -24;
                     -63 -62 -60 -57 -53 -48 -42]
m      % Ismember. Implicit display
       % STACK: 1

Python 3, 84 bytes
lambda n:1in set([((8*(n+(i*(i+1)/2)*3)+1)**0.5)%4==1for i in range(n)])or n in[0,1]

Try it online!

Ruby, 65 57 52 48 bytes
->n,b=0{b+=1;(8*n-2+3*b*b)**0.5%1==0||b<n&&redo}

Try it online!
Inspired by xnor's python answer

05AB1E, 11 bytes
ÅT3*+8*>Å²Z

Try it online!
Explanation
ÅT            # get a list of triangle numbers upto input
  3*          # multiply each by 3
    +         # add input to each
     8*       # multiply each by 8
       >      # increment each
        Å²    # check each for squareness
          Z   # max

This is based on the fact that a number T is triangular if 8T+1 is an odd perfect square.
We start on the list of triangles we could truncate, calculate the possible larger triangles based on them and check if it in fact is triangular.

Japt, 16 bytes
ò å+ d@Zd_-3*X¶U

Try it | Check all test cases

Explanation
                     :Implicit input of integer U
ò                    :Range [0,U]
  å+                 :Cumulative reduction by addition
     d@              :Does any X in array Z return true when passed through this function?
       Zd_           :  Does any element in Z return true when passe through this function?
          -3*X       :    Subtract 3*X
              ¶U     :    Check for equality with U

Alternative
ò å+ £Zm-3*XÃdøU

Try it

Add++, 36 bytes
D,g,@,.5^di=
L,ßR¬+A↑>3€*A€+8€*1€+ºg

Try it online!


text:
Stereographic projection of polyhedra
You will create a program that generates the stereographic projection of polyhedra.
In particular, to keep things simple, we'll only focus on n-chamfered dodecahedron.
Given a natural number n as input, and also a natural number d your program will output an d pixels by d pixels image which is the stereographic projection of the dodecahedron which has been chamfered n times. This is code-golf, so the shortest program wins!
Examples

0 ->  (the regular dodecahedron)

Notes

You must select a color for the background, edges, and vertices. The color of the edges and vertices may coincide, but the color of the background must coincide with neither.
You may treat the polyhedra either spherically or straight edged.
The center of the image must be the center of a pentagon.
Since stereographic projection results in an infinitely large image, you only need to have at least 75% of the vertices in the image.
EDIT: Since I never specified you can chamfer by any non-trivial amount. That being said, it would be nice if it looked like the images of chamfering below (i.e. almost regular).

Smiley Bonus
The n-chamfered dodecahedron is the $GP(2^n,0)$ goldberg polyhedron (where $GP(x,y)$ means a polyhedron consisting of hexagons and pentagons where if you start at one pentagon and move x spaces one direction, turn 60 degrees clockwise, and y spaces in that direction, you end up at another pentagon). Therefore, it might be easier to just calculate $GP(x,y)$ for arbitrary $x$ and $y$. If you do, you get a Smiley bonus (I can't award points since the challenge has already started).
Background
A dodecahedron is polyhedron with 12 sides, each pentagons. It looks like this

When you chamfer a shape, you replace each face with a smaller face, and each edge with a hexagonal face. For instance, here is what happens when you chamfer a dodecahedron (note, this is not the same shape as a soccer/football)

Here is what it looks like when you chamfer it again (i.e. n=2) polyHédronisme (sorry, the image export doesn't seem to be working).
Stereographic projection means that vertices of the polyhedron on a sphere. Place a plane tangent to it, and point on the opposite side of the sphere (called the view point). Then, draw a line between each point of the polyhedron and the view point. Extend this line to the plane, and map that point there. Do this for all the points. See above for an example of the stereographic projection of the dodecahedron.

Comments are not for extended discussion; this conversation has been moved to chat.

837 Bytes : Javascript/HTML + d3.js + d3-delaunay + d3-geo-voronoi*
I believe I have a solution for this challenge. It relies on d3's geographic features: projections and pathing along great circles, d3-delaunay (a voronoi generator) and d3-geo-voronoi (a geographical voronoi extension to d3-delaunay).
The approach I've taken is fairly simple:

Take the centers of the faces of a regular dodecahedron (as lat/long pairs).
Create a spherical voronoi diagram of the centers (replicating the dodecahedron, contained in a sphere)
If more chamfering is needed, calculate the midpoint of each edge of the spherical voronoi diagram, add these to the list of centers, go back to step 2.
Project and draw

Using the midpoint from each edge as a new face center creates a new face for every edge when running through  the voronoi generator. This chamfering is fairly regular, the midpoint of each edge should be in the middle of a new face when chamfering. This does not mean the hexagons are regular, hexagons cannot be regular when chamfering twice or more (if I'm not mistaken).
Here's the implementation in 837 bytes:
<input><input>
d
<canvas>

Input is in the form of two html input fields, first one is the size of the drawing, the second one is the number of times to chamfer, clicking "d" will draw).
And in snippet form (with some minor interface changes: input s is size, input n is times to chamfer, click "draw" to draw):

_="canvas",O=d3,$=O.select,$("p").on("click",()=>{N=O.selectAll("input").nodes(),w=N[0].value,n=N[1].value,$(_).attr("width",w).attr("height",w),a=31.71801,b=58.28198,c=121.71801,C=[[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]],s=$(_).node().getContext("2d"),p=O.geoStereographic().scale(60/960*w).rotate([-b,0]).translate([w/2,w/2]).clipAngle(170),P=O.geoPath(p,s),s.clearRect(0,0,w,w),D=C=>O.geoVoronoi()(C),M=v=>v.mesh().coordinates.map((c)=>O.geoInterpolate(c[0],c[1])(0.5)),v=D(C);for(i=0;i<n;i++){C.push(...M(v)),v=D(C)}v.polygons().features.forEach(f=>(s.beginPath(),P(f),s.stroke()))})
s<input>n<input>
draw
<canvas>

slightly modified for snippet view as noted, also as there are other nodes in the snippet to navigate, so there is a change there
If rendered as 3d, this produces something along the lines of (chamfered five times):

Original pentagons are in orange - they are separated by 31 hexagons.
An example with the sterographic (chamfered 6 times):

*Note
The above may not conform to scoring rules very well. Without using new (relative to challenge) updates to dependecies, but replacing those with poor and incomplete minimization:
4454 Bytes : d3.js (v4) + d3-delaunay (v2)
d3-geo-voronoi has been altered since the challenge has been posted in a way that enables the above solution. While it wasn't altered by me, nor to address this challenge, I'll include the longer solution that relies on only d3.js and d3-delaunay (versions that predate the challenge) and incorporates the necessary parts of d3-geo-voronoi:
<input><input>
draw
<canvas></canvas></script>

Lastly, here's an animated ungolfed snippet to show the workings:

var n = 3; // chamfer this many times.

var a = 31.71801891964135;
var b = 58.28198108035894;
var c = 121.71801891964117;
var centroids = [[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]];

var getDiagram = function(centroids) {
 return d3.geoVoronoi()
  .x(function(a) {
   return a[0]
  })
  .y(function(a) {
   return a[1]
  })
  (centroids);
}

var getCenters = function(v) {
 return v.mesh().coordinates.map(function(c) {
  return d3.geoInterpolate(c[0],c[1])(0.5);
 })
}

// Starting voronoi:
var voronoi = getDiagram(centroids);

for (var i = 0; i < n; i++) {
 centroids.push(...getCenters(voronoi));
 voronoi = getDiagram(centroids);
}

var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");
var projection = d3.geoStereographic().scale(60).clipAngle(170).translate([480,480])
var path = d3.geoPath().projection(projection).pointRadius(1).context(context);

// animate:
d3.interval(function(elapsed) {
    projection.rotate([ -elapsed / 200, 0 ]);
 context.clearRect(0,0,960,960);
 voronoi.polygons().features.forEach(function(d) {
  context.beginPath();
  path(d)
  context.stroke();
 })
}, 50);
<canvas width="960" height="960"></canvas>

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Sort by shuffling blocks
Block shuffle sort
The block shuffle sort is a (rather artificial) method of sorting a list.
It works as follows, illustrated by an example.
[6, 1, 0, 3, 2, 4, -2, -1]
                            Break list into contiguous blocks
[6][1, 0][3, 2, 4][-2, -1]
                            Sort each block
[6][0, 1][2, 3, 4][-2, -1]
                            Sort blocks lexicographically
[-2, -1][0, 1][2, 3, 4][6]
                            Concatenate
[-2, -1, 0, 1, 2, 3, 4, 6]

The partition into contiguous blocks can be chosen arbitrarily.
However, not all choices of blocks will yield a sorted list at the end:
[6, 1, 0, 3, 2, 4, -2, -1]
[6, 1, 0][3, 2, 4][-2, -1]
[0, 1, 6][2, 3, 4][-2, -1]
[-2, -1][0, 1, 6][2, 3, 4]
[-2, -1, 0, 1, 6, 2, 3, 4]

If all blocks have length 1, or if there is only one block, then the result will of course be sorted.
But these are rather extreme cases.
In this challenge, your task is to find a balance between the number of blocks and the maximum length of a block.
The task
Your input is a nonempty list of integers L, taken in any reasonable format.
Your output shall be the smallest integer N such that L can be block shuffle sorted so that the number of blocks and the length of each block are at most N.
The lowest byte count in each language wins.
Standard code-golf rules apply.
Test cases
[5] -> 1
[1,2] -> 2
[0,2,1,-1] -> 3
[-1,0,2,1] -> 2
[9,3,8,2,7] -> 4
[9,2,8,3,7] -> 3
[5,9,3,7,2,4,8] -> 7
[-1,-2,1,2,-1,-2,7] -> 4
[6,1,0,3,2,4,-2,-1] -> 4
[12,5,6,-6,-1,0,2,3] -> 3
[1,0,1,0,1,0,1,0,1,0] -> 6
[1,2,1,3,1,2,3,2,4,3] -> 5
[7,7,7,7,8,9,7,7,7,7] -> 4

Brachylog, 23 22 20 19 bytes
Thanks to Zgarb, H.PWiz and Fatalize for saving some amount of bytes.
~cᶠ{oᵐoc≤₁&≡ᵃlᵐ⌉}ˢ⌋

Try it online!
I'm sure there's more to golf here...
Explanation
~cᶠ      Find all lists that concatenate into the input, i.e. all partitions
         of the input.
{        Discard all partitions for which this predicate fails, and replace
         the rest with the output of this predicate.
  oᵐ       Sort each sublist of the partition.
  o        Sort the entire list.
  c≤₁      And require concatenation of the result to be sorted.
  &        Then:
  ≡ᵃ       Append the partition to itself.
  lᵐ       Map "length" over this list, i.e. we get the length of each block, as
           well as the length of the partition itself.
  ⌉        Take the maximum.
}ˢ
⌋        Take the minimum of all those maxima.

Jelly, 17 bytes
Ṣ€ṢF
ŒṖÇÐṂ+Z$€L€Ṃ

Try it online!
Alternate version, 15 bytes, postdates challenge
In the latest version, Ɗ combines three links into a monadic chain. This allows the following golf.
ŒṖṢ€ṢFƊÐṂ+ZLƊ€Ṃ

Try it online!
How it works
Ṣ€ṢF          Helper link. Argument: P (partitioned array)

Ṣ€            Sort each chunk.
  Ṣ           Sort the sorted chunks.
   F          Flatten.

ŒṖÇÐṂ+Z$€L€Ṃ  Main link. Argument: A (array)

ŒṖ            Generate all partitions of A.
  ÇÐṂ         Keep those for which the helper link returns the minimal array, i.e.,
              those that return sorted(A).
     +Z$€     Add each partition to its transpose.
              Due to how Jelly vectorizes, the length of the sum is the maximum of
              the length of the operands, and the length of the transpose is the
              length of the array's largest column.
         L€   Take the length of each sum.
           Ṃ  Take the minimum.

Stax, 28 26 25 24 23 bytesCP437
é%(>ù│ê²☻û◙T╠►╜◘íaæAtI╥

Run and debug online!
Credits to @recursive for saving 3 bytes.
Stax is a bit verbose here. It takes two bytes to sort an array by default, two bytes to get the maximum/minimum of an array and two bytes to flatten an array. Anyway I am still posting the solution  and hope there can be helpful suggestions on how to improve it  there is.
Explanation
Uses the unpacked version to explain.
%cFxs|!F{{omo:f:^!C_Mch\%|m
%cFxs|!F                        Do for all partitions, grouped by number of sub-arrays
                                    Grouping by number of sub-arrays in this problem does not help but it's the default
        {{om{o                  Sort inside block then sort blocks lexicographically
              :f:^              The result when flattened is sorted
                  !C            Skip the rest of the loop if the last line is false
                    _|<         Take the current partition, pad to the longest

                       h        Take the first element, whose length is now the maximum of all sub-arrays in the original partition
                        \       Zip with the current partition, the shorter one is repeated
                         %      Number of elements
                                Which is the maximum of all sub-array sizes and the number of sub-arrays in the current partition
                          |m    Take the minimum among all choices of partitions

This gives 25.

This is a kind of disappointing performance for stax, but I'm going to keep looking for savings.

http://staxlang.xyz/#c=%E2%95%A6%C6%92%E2%88%A9%E2%94%80%E2%95%AAZ%E2%99%80%E2%95%A6%C3%A1%E2%98%BB%E2%94%80%E2%94%8Cj%E2%80%BC+BI%E2%95%9F%CE%A9z%C2%B6%E2%8C%90%E2%95%A4%E2%96%84&i=%5B5%5D%0A%5B1%2C2%5D%0A%5B0%2C2%2C1%2C-1%5D%0A%5B-1%2C0%2C2%2C1%5D%0A%5B9%2C3%2C8%2C2%2C7%5D%0A%5B9%2C2%2C8%2C3%2C7%5D%0A%5B5%2C9%2C3%2C7%2C2%2C4%2C8%5D%0A%5B-1%2C-2%2C1%2C2%2C-1%2C-2%2C7%5D%0A%5B6%2C1%2C0%2C3%2C2%2C4%2C-2%2C-1%5D%0A%5B12%2C5%2C6%2C-6%2C-1%2C0%2C2%2C3%5D%0A%5B1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%2C1%2C0%5D%0A%5B1%2C2%2C1%2C3%2C1%2C2%2C3%2C2%2C4%2C3%5D%0A%5B7%2C7%2C7%2C7%2C8%2C9%2C7%2C7%2C7%2C7%5D&a=1&m=2

That's just ... amazing.

Thanks.  I found it amusing that the hyperlink used exactly the maximum comment size, after replacing "https://" with "http://".

That's interesting. Actually I have been thinking that the JS interpreter should be able to encode all those unicode symbols in the URL in a more efficient way ...

Yes, I think you're right.  It shouldn't be too difficult to improve it quite a bit.  Also, I could have replaced commas in the input with spaces, which are also legal array separators.  I think I will work on something like this for 1.0.5

I look forward to the update and the online deployment.

@recursive Consider using Base64? (like TIO)

@WeijunZhou:  The new version of stax has been released, but here's a 23 byte solution that doesn't use any new language features.  It would have worked at the time this challenge was posted.

Well, I originally used :^ but I thought you changed it for good reasons ... Updated. Also, any advice for this?

Brachylog, 17 bytes
~c₎{oᵐoc≤₁&lᵐ⌉≤}ᵈ

Try it online!
Explanation
This is a self-answer; I designed this challenge with Brachylog in mind and found ~c₎{…}ᵈ an interesting construct.
The built-in c concatenates a list of lists.
If it is given a subscript N, it requires the number of lists to be N.
The symbol ₎ modifies a built-in to take a pair as input and use its right element as the subscript.
Thus c₎ takes a pair [L,N], requires that the number of lists in L is N, and returns the concatenation of L.
When run in reverse, ~c₎ takes a list L and returns a pair [P,N], where P is a partition of L into N blocks.
They are enumerated in increasing order of N.
The metapredicate ᵈ transforms an ordinary predicate into one that checks a relation between the two elements of a pair.
More explicitly, {…}ᵈ takes a pair [A,B], checks that A{…}B holds, and outputs B.
I use it to verify that P can be block-sorted and only contains lists of length at most N.
~c₎{oᵐoc≤₁&lᵐ⌉≤}ᵈ  Input is a list, say L = [9,2,8,3,7].
~c₎                Guess the pair [P,N]: [[[9],[2],[8,3,7]],3]
   {           }ᵈ  Verify this predicate on P and N and return N:
    oᵐ              Sort each list in P: [[9],[2],[3,7,8]]
      o             Sort lexicographically: [[2],[3,7,8],[9]]
       c            Concatenate: [2,3,7,8,9]
        ≤₁          This list is nondecreasing: true.
          &lᵐ       Length of each list in P: [1,1,3]
             ⌉      Maximum: 3
              ≤     This is at most N: true.

Note that P may contain empty lists.
This ensures correctness also in those cases where the maximal length of a block is greater than the number of blocks.

Python 2, 186 146 bytes
lambda l:min(max(map(len,z+[z]))for z in p(l)if sum(s(z),[])==s(l))
p=lambda l:[q+[s(l[i:])]for i in range(len(l))for q in p(l[:i])]or[l]
s=sorted

Try it online!
The second function is taken from this tip by feersum.

Ruby, 158 bytes
f=->l,i=[],s=l.size,m=s{k=*l;i.sum==s&&i.map{|z|k.shift(z).sort}.sort.flatten==l.sort&&[m,[i.size,*i].max].min||i.sum<s&&(1..s).map{|z|f[l,i+[z],s,m]}.min||m}

Try it online!

Pyth,  24 23  20 bytes
hSmeSlMs]Bd.msSSMb./

Test suite.
How it works
hSmeSlMs]Bd.msSSMb./ – Full program. Hereby, Q represents the input.
                  ./ – All possible partitions of Q.
           .m        – Take the partitions which yield a minimal (i.e. sorted) list over:
             sSSMb   – Sorting function. Uses the variable b.
               SMb   – Sort each list in each partition b.
              S      – Sort the partition b.
             s       – And flatten (by 1 level).
  meSlMs]Bd          – Map. Uses a function whose variable is d.
        ]Bd          – Pair d with its wrapping in a singleton list. Returns [d, [d]].
       s             – Flatten (by 1 level). Returns [*d, d], where "*" is splatting.
     lM              – Take the length of each element.
   eS                – Retrieve the maximal length.
hS                   – Return the minimum element of the list of maximal lengths.

APL (Dyalog Classic), 71 67 bytes
{⌊/(⌈/≢,≢¨)¨T/⍨{S[⍋S]≡∊⍵[⍋↑⍵]}¨T←{⍵[⍋⍵]}¨¨⊂∘S¨(-≢S)↑¨2⊥⍣¯1¨⍳2*≢S←⍵}

⎕IO must be 0
Try it online!
How?

⌊/ - Find the minimum of ...
(⌈/≢,≢¨) - ... the maximum of the length and number of elements ...
¨ - ... of each element of ...
T/⍨ - ... the elements that ...
{S[⍋S]≡∊⍵[⍋↑⍵]}¨ - ... are sorted when flattened, of ...
T←{⍵[⍋⍵]}¨¨ - ... the sorted elements of the elements of ...
⊂∘S¨(-≢S)↑¨2⊥⍣¯1¨⍳2*≢S←⍵ - ... the partitions of the argument (along with some junk)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Sparse Protractor
Given some positive integer n, design a protractor with the fewest number of marks that lets you measure all angles that are an integral multiple of 2π/n (each in a single measurement).
Details
As an output, you may output a list of integers in the range 0 to n-1 (or 1 to n) that represent the position of each mark. Alternatively you can output a string/list of length n with a # at the position of each mark and a _ (underscore) where there is none. (Or two different characters if more convenient.)
Example: For n = 5 you need exactly 3 marks to be able to measure all angles 2π/5, 4π/5, 6π/5, 8π/5, 2π by setting (for example) one mark at 0, one mark at 2π/5 and one mark at 6π/5. We can encode this as a list [0,1,3] or as a string ##_#_.

Examples
Note that the outputs are not necessarily unique.
n:  output:
 1  [0]
 2  [0,1]
 3  [0,1]
 4  [0,1,2]
 5  [0,1,2]
 6  [0,1,3]
 7  [0,1,3]
 8  [0,1,2,4]
 9  [0,1,3,4]
10  [0,1,3,6]
11  [0,1,3,8]
20  [0,1,2,3,6,10]

PS: This is similar to the sparse ruler problem, but instead of a linear scale (with two ends) we consider a circular (angular) scale.
PPS: This script should compute one example of a set of marks for each n. Try it online!
PPPS: As @ngn pointed out, this problem is equivalent to finding a minimal difference base of a cyclic group of order n. The minimal orders are listed in http://oeis.org/A283297 and some theoretical bounds are found in https://arxiv.org/pdf/1702.02631.pdf

Related.

Borderline dupe, with exact overlap when n = q^2 + q + 1 for prime power q.

@PeterTaylor I don't see why you think it is a dupe. And can you elaborate in what way there is an "overlap"?  Even though there are similarities, these are two very different problems. Furthermore this is [tag:code-golf] and challenge you linked doesn't even include the size of the program in its scoring.

They're not two very different problems. Read the OEIS link in your PPPS: the "difference set of Singer" referred to there is precisely the Golomb ruler generated by the projective field method implemented in my answer. I take the point that the scoring method is different.

MATL, 20 bytes
:qGZ^!"G:q@&-G\m?@u.

This runs out of memory on TIO for inputs beyond 8.
Try it online!
How it works
This generates the Cartesian power of [0 1 ... n-1] with exponent n, and uses a loop to test each Cartesian tuple. The test consists in computing all pairwise differences of element if the tuple, and seeing if those differences modulo n include all numbers 0, 1, ..., n-1.
As soon as a Cartesian tuple fulfilling the condition is found the loop is exited, and the unique entries in that tuple are printed as the solution.
This works because given u > v, a sufficient set of tuples with u unique entries are guaranteed to be tested earlier than any tuple with v unique entries. A "sufficient set" means that if none of the tuples in that set are a solution then no other tuple with the same number of unique entries is a solution.
For example, for n = 3 the Cartesian tuples are as shown below, where each row is a tuple:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
 ···
2 2 1
2 2 2

The first tuple, 0 0 0, is the only relevant tuple with 1 unique value. Even if 1 1 1 and 2 2 2 will appear much later, 0 0 0 is a solution if and only if those are. So the singleton set formed by the tuple 0 0 0 is a sufficient set for u = 1.
The second and third tuples, namely 0 0 1and 0 0 2, form a sufficient set for u = 2; that is, they cover all cases with 2 unique values. The fourth tuple, 0 1 0, will never be selected as solution, because 0 0 1 will have been tested first. Similarly, the tuple 0 2 0 will never be selected because it appears later than 0 0 2. Tuples such as 2 2 1 will never be selected as solution because the 0 0 1 is equivalent (modulo n and up to duplicated values) and appears first.
Etc.

Commented code:
:q         % Push [0 1 ... n-1], where n is the input (implicit)
GZ^        % Cartesian power with exponent n. Gives an (n^n) × n matrix
           % where each row is a Cartesian tuple
!          % Transpose. Now each Cartesian tuple is a column
!"         % For each column (that is, each Cartesian tuple)
  G:q      %   Push [0 1 ... n-1] (*)
  @        %   Push current column
  &-       %   Matrix of pairwise differences (**)
  G\       %   Modulo n, element-wise
  m        %   Ismember function: for each entry in (*), gives true iff
           %   it is present in (**)
  ?        %   If all entries are true
    @      %     Push current column
    u      %     Unique entries. This is the solution
    .      %     Break loop
           %   End (implicit)
           % End (implicit)
           % Display (implicit)

Jelly, 13 bytes
ŒPðṗ2I%QLðÐṀḢ

Try it online!
How it works
ŒPðṗ2I%QLðÐṀḢ  Main link. Argument: n (integer)

ŒP             Powerset; generate all subsequences of [1, ..., n].
  ð       ÐṀ   Begin a dyadic chain. Call it with all subsequences S as left
               argument and n as right one. Return the array of all sequences for
               which the chain returns the maximal result, i.e., [0, ..., n-1].
   ṗ2              Cartesian power 2; generate all pairs of elements of S.
     I             Increments; map each pair [x, y] to [y-x].
      %            Map each [y-x] to [(y-x)%n].
       Q           Unique; deduplicate the array of modular difference singletons.
        L          Take the length.
         ð     Begin a new, dyadic chain.
               Left argument: S' (filted subsequences). Right argument: n
            Ḣ  Take the first element of S'.
               Since S was sorted by length, so is S', so the first element of S'
               is the shortest subsequence that satisfies the condition.

Stax, 26 21 bytes
Åæ4&╕u◙╩►s∙Φ▬═(0~ d+Q

Run and debug online!
 Right now the online version fails for input 20 but this bug has been fixed and is yet to be deployed to the online interpreter  Deployed. Beware it takes some time to run the 20 case.
Explanation
Turns out that due to way pairwise difference is calculated, I don't need to worry about the equivalence of k and x-k here. Saving 5 bytes.
Uses the unpacked version to explain.
rS{%o~{;i@c:2{E-x%mu%x<wm
r                            [0..`x`], where `x` is input
 S                           Powerset
  {%o~                       Sort by length
      {;i@             w     For each element in the powerset
          c:2                All pairs
             {    m          Map each pair `[p,q] to
              E-                 `q-p`
                x%               `(q-p)%x`
                   u%        Count of unique modulo differences
                     x<      Loop until the count of unique modulo differences is larger than the input(`n`)
                             Now we have found a valid set in the powerset
                        m    Output the members of the set,one element per line.

By enforcing the requirement that 0 and 1 both be members of the answer, we can generate the powerset with [2..x] instead of [0..x] and then add the 0 and 1 manually to every element in the powerset. It is more efficient but need to handle the input 1 specially and costs more bytes.

Jelly, 17 bytes
_þ¹F%³³Ḷ¤ḟ
ŒPÇÐḟḢ

Try it online!
-1 byte thanks to Mr. Xcoder

You don't need the leading R.

@Mr.Xcoder oh right, thanks!

Python 2, 148 bytes
from itertools import*
def f(n):
 r=range(n)
 for i in r:
  for p in combinations(r,i+1):
   if all(any((y+x)%n in p for y in p)for x in r):return p

Try it online!


text:
Crazy but Rational Bases
We have many challenges based on base 10, base 2, base 36, or even base -10, but what about all the other rational bases?
Task
Given an integer in base 10 and a rational base, return the integer in that base (as an array, string, etc.).
Process
It's difficult to imagine a rational base, so let's visualize it using Exploding Dots:
Consider this animation, expressing 17 in base 3:

Each dot represents a unit, and boxes represent digits: the rightmost box is the one's place, the middle box is the 3^1 place, and the leftmost box is the 3^2 place.
We can begin with 17 dots at the one's place. However, this is base 3, so the ones place has to be less than 3. Therefore, we "explode" 3 dots and create a dot on the box to the left. We repeat this until we end up with a stable position with no explodable dots (i.e. 3 dots in the same box).
So 17 in base 10 is 122 in base 3.

A fractional base is analogous to exploding some number of dots to more than one dots. Base 3/2 would be exploding 3 dots to create 2.
Expressing 17 in base 3/2:

So 17 in base 10 is 21012 in base 3/2.

Negative bases work similarly, but we must keep track of signs (using so-called anti-dots, equal to -1; represented by an open circle).
Expressing 17 in base -3:

Note, there are extra explosions to make the sign of all the boxes the same (ignoring zeros).
Thus, 17 in base 10 is 212 in base -3.
Negative rational bases work similarly, in a combination of the above two cases.
Rules

No standard loopholes.
The sign of each "digit" in the output must be the same (or zero).
The absolute value of all digits must be less than the absolute value of the numerator of the base.
You may assume that the absolute value of the base is greater than 1.
You may assume that a rational base is in its lowest reduced form.
You may take the numerator and the denominator of the base separately in the input.
If a number has multiple representations, you may output any one of them. (e.g. 12 in base 10 can be {-2, -8} and {1, 9, 2} in base -10)

Test cases:
Format: {in, base} -> result
{7, 4/3}        ->  {3, 3}
{-42, -2}       ->  {1, 0, 1, 0, 1, 0}
{-112, -7/3}    ->  {-6, -5, 0, -1, 0}
{1234, 9/2}     ->  {2, 3, 6, 4, 1}
{60043, -37/3}  ->  {-33, -14, -22, -8}

Since some inputs may have multiple representations, I recommend testing the output using this Mathematica snippet on TIO.
This is code-golf, so submissions with shortest byte counts in each language win!

For more information on exploding dots, visit the global math project website! They have a bunch of cool mathy stuff!

Related

Python 2, 42 39 bytes
n,a,b=input()
while n:print n%a;n=n/a*b

Try it online!
Thanks to @xnor for finding the shorter form.
Obsolete version (42 bytes):
f=lambda n,a,b:n and[n%a]+f(n/a*b,a,b)or[]

Try it online!
Parameters: input, numerator (with sign) and denominator.
Returns an array, lowest digit first.
This just works because the division and modulo in Python follows the sign of the denominator, so we don't have to care about same signs explicitly.
Test case output:
f(7, 4, 3)       == [3, 3]
f(-42, -2, 1)    == [0, -1, -1, -1, -1, -1, -1]
f(-112, -7, 3)   == [0, -1, 0, -5, -6]
f(1234, 9, 2)    == [1, 4, 6, 3, 2]
f(60043, -37, 3) == [-8, -22, -14, -33]

Unusually, it looks like a program is shorter.

@xnor Thanks, I always forget that way to write something...

Aheui (esotope), 91 bytes
벙수벙섞벙석
희빠챠쌳뻐삭빠빠싻싸삯라망밣밭따맣사나삮빠싸사땨

Try it online!
Takes integer, numerator of base, and denominator of base.
Due to the limitation of the TIO interpreter, each input must end with a newline.
Implementation of @Bubbler's Python 2 answer. Luckily, this Aheui interpreter is written in Python, so we can use the same trick.

o_O what on earth is this language... D:

05AB1E, 11 10 bytes
[D_#²‰`,³*

Try it online!
Takes integer, numerator of base and denominator of base like all answers. Since 05AB1E interpreter is written in Python(?), Bubbler's Python 2 answer trick can be used in 05AB1E too.
Explanation

[D_#²‰`,³*
[                                        Infinite Loop
 D_#                                     If the number is 0, exit loop (implicit input
                                         in the first iteration)
     ²                                   Get the numerator of base
      ‰                                  Divmod
       `                                 Push all elements into the stack
        ,                                Print the remainder
         ³                               Get the denominator of base
          *                              Multiply it.

So the program works roughly the same as this Python code:

i1, i2, i3 = input()
stack = []
while 1:
 stack = (stack or [i1])
 stack += [stack[-1]]
 if not stack[-1]: break
 stack += [i2]
 stack = stack[:-2] + [divmod(stack[-2], stack[-1])]
 stack = stack[:-1] + list(stack[-1])
 print stack[-1]
 stack = stack[:-1]
 stack += [i3]
 stack = stack[:-2] + [stack[-2] * stack[-1]]

11 > 10 Thanks Neil

I think you can use _ instead of 0Q here.

@Neil Oh true, I forgot about negative boolean!


text:
Balanced Zero-One Encoding
Task
Encode a string that entirely consists of uppercase alphabets (A-Z) using only zeros and ones, using your own favorite scheme. But the rule isn't that simple!
Rules

Your program/function must correctly handle any valid input string of length 8.
The results must have the same length for all inputs.
The results must be distinct for distinct inputs.
The results must be as short as possible.
The results must be zero-one balanced (have number of ones similar to that of zeros). They don't have to be equal (i.e. perfectly balanced), but your score will be penalized for that.

You don't have to provide a program/function that decodes your encoding.
Input and Output

You can decide to accept any set of 26 distinct printable ASCII characters instead of A-Z.
You can decide to output any pair of distinct printable ASCII characters instead of 0 and 1.
You are not allowed to output an integer instead of a bit string, since it may have leading zeros and it's unclear if you actually met the rule 2.
If you decide to deviate from the default (A-Z input and 01 output), you must specify the input/output character sets in your submission.

Scoring

Base score: Code size, or 1 if your program happens to be empty.
Penalties

Penalty for length: multiply 1.5 ** (encoded length - 42)
There is no bonus for being shorter; 42 is the minimal length for a perfectly balanced encoding of 8-length strings with alphabet size 26.
Penalty for being unbalanced: multiply 2 ** max(abs(ones - zeros) for every valid input of length 8), where ones and zeros are the counts of 1 and 0 in each output, respectively.
Your submission must either show a worst-case example (input/output) or theoretical explanation on the penalty value.

The lowest score wins.

Example Submission
Hypothetical esolang, 0 Bytes, Score 74733.8906
Here is a hypothetical esolang, where an empty program prints out all the ASCII codes of input's characters in binary.

For example, if you give AAAAAAAA as input, the program will print 1000001 8 times in a row, i.e. 10000011000001100000110000011000001100000110000011000001.
The input alphabet is chosen to be CEFGIJKLMNQRSTUVXYZabcdefh. This way, all of the chars are converted to seven digits in binary, and the zero-one counts differ only by one per char (they all have three 1's and four 0's or vice versa when converted to binary).
The output length is always 56, and the worst-case unbalance occurs on the inputs like CCCCCCCC, where zeros appear 8 more times than ones.
Therefore, the score of this submission is 1.5 ** (56 - 42) * 2 ** 8 == 74733.8906.

Sandbox: https://codegolf.meta.stackexchange.com/a/14908/78410

can I use my hypothetical esolang in which the empty program accepts a number N in letter-encoded 26-ary and outputs the N-th possible 42-bit sequence of sum 21?

@ngn - does your hypothetical language meet our accepted criteria? - EDIT ah input is always [A-Z] - I guess that's easy enough... :)

@JonathanAllan yeah, Balboolenc is transpiled to Python - the empty program does as described above, any other program remains intact :)

Can the code take really long to run? For example, I might iterate over all length-42 binary strings to find balanced ones.

@xnor It's fine as long as you can prove the score of your submission.

Can we output a list of ones and zeroes or does it have to be a string?

@Dennis List output is OK, as in any other challenges.

Penalty for length: multiply 1.5 ** (encoded length - 42) do you mean 1.5 ** max(encoded length - 42, 0)?

The whole question is lead into "mustn't have unbalance, must be in 42 digits, who care real running time"

Jelly, 18 bytes
2Ḷx21Œ!Q
O_65ḅ26ị¢

Try it online!
-1 byte thanks to caird coinheringaahing
might remember to re-add the explanation since it was restructured for golfing

E x p l a n a t i o n?

@EsolangingFruit added

-1 byte by restructuring

@cairdcoinheringaahing thanks!

Stax, 11 bytes, 0 penalty, Score 11
This program uses [0-9A-P] for input and [01] for output.
ö■▄←·ï↨≡⌐╠H

Run and debug it online - click the run button to start.  The first four test cases run in milliseconds.  The fifth in seconds.  The sixth in millenia.
The corresponding ascii representation of this program is this.
A$21*,26|bD|N

It leans heavily on the |N instruction, which gets the subsequent permutation of an array.
A$21*           "10" repeated 21 times
     ,26|b      get input and decode it as a base 26 number
          D|N    ... that many times get the next lexicographic permutation

All outputs are permutations of the initial string.  It has 21 zeroes and 21 ones.  Therefore, all outputs are 42 characters, and perfectly balanced.

Pyth, 20 19 14 bytes, Max Diff: 0, Length: 64, Score: 149636.5528 142154.7251 104745.5869
sm@S.{.p*`T4xG

Try it online!
Uses the lower case alphabet ([a-z]) instead of uppercase. Can use uppercase by replacing G with rG1, at the cost of 2 bytes.
I could have translated HyperNeutrino's Python 3 answer for a better score, but frankly, I want an answer that actually works.

Python 2, 779 645 bytes, Max(Diff) = 0, Length = 48, Score = 7346.95
def f(s):
 a,b=0,""
 for i in s:a=a*26+ord(i)-65
 a+=56*252**4
 for i in range(5):b=bin((int("4lnk28t9vtqgfrpfda9uyfrjhcjwjvno6aec2nwegi0g4mnublc05dher8fjm4s5gh55lu87a4itmc74t6tozcsfdbxkg82frwljy0wam1jht98g2j0bma021v5d48pwq0fklv0n1ltrxft1fpk5gt5mx5fj4p2mjqqpvcylt1xayxf1iwdmyoxgfvl7oui1oo6147bm9rqpqut9ns8hhjc77t3pqy48otovrsm1t4mmleumspkuef66ma1vi0l4mtkwaeeizuvvds9fro3vhc0mrn6ox17rdpk7xw747qf28934u5jci5q1qj81i7dyf7rf0x7hb19xm93xhxsgh4w8ifs6fhynsddbo9j938ewfvhjlbpiz50n5hanmno6c89blyx50e89z7vjq2ho2r2u2wwyu4q18kv4fi1nhmfbgjbnkdayr5kblaped4fo5u97bi9a67d89irxa0r9cinmnohfgjmh5fhkcr33",36)>>a%252*10)&1023)[2:].rjust(10,"0")+b;a/=252
 return b[2:]

Try it online!
The magic number
4lnk28t9vtqgfrpfda9uyfrjhcjwjvno6aec2nwegi0g4mnublc05dher8fjm4s5gh55lu87a4itmc74t6tozcsfdbxkg82frwljy0wam1jht98g2j0bma021v5d48pwq0fklv0n1ltrxft1fpk5gt5mx5fj4p2mjqqpvcylt1xayxf1iwdmyoxgfvl7oui1oo6147bm9rqpqut9ns8hhjc77t3pqy48otovrsm1t4mmleumspkuef66ma1vi0l4mtkwaeeizuvvds9fro3vhc0mrn6ox17rdpk7xw747qf28934u5jci5q1qj81i7dyf7rf0x7hb19xm93xhxsgh4w8ifs6fhynsddbo9j938ewfvhjlbpiz50n5hanmno6c89blyx50e89z7vjq2ho2r2u2wwyu4q18kv4fi1nhmfbgjbnkdayr5kblaped4fo5u97bi9a67d89irxa0r9cinmnohfgjmh5fhkcr33 (in base 36), or its decimal equivalent 382136276621246556626597379364678993894472503063952720559883124988542417847157286833446006767955087631166943136913765901237281892296575754126024183763829277879554548743231384272055945084065681774297483130020386641869860456147616177702938121538230311395513497506285733567467605871232294046704309941152721616618474501854355102646152223338484615876165254236449912858255665248186687952137487016925761633237335983620006273901509768720506129789443353730706676483647298576692613113269388239830925662977837917272690235355742330377154505179476767457756888107428475384947712227312747517748632498691058764154580934614231152483398774630508576533263098942260213967880819240793990219283490212843120923539516962682466148372296338428497778127570401190309339992457562121354271,  encodes all 252 permutations of 5 0s and 5 1s.
The algorithm first converts A-Z into 0-25 and treat it as a base-26 number, then add 56*252**4.
Then, the number is converted to a 5-digit base-252 number, and substitute with the corresponding permutation of 5 0s and 5 1s.
After that, delete the first 2 bits, which is guaranteed to be 01. Then we have encoded the string to a 48-bit string, which consists of exactly 24 0s and 24 1s.

Pretty sure the penalties have to be multiplied (that is, your score is 7346.953125).

@HyperNeutrino Oh I though it is addition ;P Edited

Perl 5, 55 bytes, max diff 0, length 42, score 56 55
This works but will take a long but doable time (ZZZZZZZZ took 2.5 days on my computer). Memory is no problem.
Uses A-Z as input and 1 and A as encoding characters. They are always perfectly balanced. Skips the first 26^7 = 8031810176 balanced combinations representing string shorter than 8 characters, but that's OK since there are 538257874440 available and I use 208827064575 and 208827064575 + 8031810176 < 538257874440.
However it actually "counts" up to to the target combination which will take very long. That's why in the TIO link I only used a too short input string (which are also supported) to demonstrate that the output is correct. Will work up to a bit more than AAAAAA before TIO times out.ZZZZZZZZ should be about 26^3 = 17576 times slower.
#!/usr/bin/perl -ap
$_=1x21 .($i=A)x21;s/(A*)(1*)1A/$2$1A1/ until"@F"eq$i++

Try it online!
The decoder is almost the same:
#!/usr/bin/perl -ap
$_=1x21 .($\=A)x21;s/(A*)(1*)1A/$2$1A1/,$\++until"@F"eq$_}{

Try it online!

JavaScript (ES8), score 22186.623779296875

f=
s=>s.replace(/./g,(c,i)=>(i%2*127^c.charCodeAt()).toString(2).padStart(7,0))
<input oninput=o.textContent=f(this.value)><pre id=o>

For even length input, always outputs 3.5* of zeros and ones, so it only pays the 1.5 ** 14 penalty. Supported characters: '+-.3569:<GKMNSUVYZ\cefijlqrtx.

Python 3, 985 135 bytes, Max Diff 0, Length 42, score 135
lambda s:C(int(s,26),21,20)
B=lambda x,y:y<1or-~x*B(x+1,y-1)//y
def C(n,o,z):p=B(o,z);x=n>=p;return z+1and[x]+C(n-p*x,o-x,z-1+x)or[1]*o

Try it online!
Courtesy of Bubbler
Ungolfed code:
import math

def binomial(x, y):
    return math.factorial(x) // math.factorial(y) // math.factorial(x - y)

def string_to_int(input_str):
    result = 0
    for i in range(0,8):
        result += (ord(input_str[i])-65)%26 * pow(26,i)
    return result

def counting_function(target, ones, zeros):
    if zeros > 0:
        position = binomial(ones+zeros-1,zeros-1)
    else:
        position = 1
    if target > position:
        if ones > 0:
            print("1", end='')
            ones -= 1
            counting_function(target-position,ones,zeros)
    else:
        if zeros > 0:
            print("0", end='')
            zeros -= 1
            counting_function(target,ones,zeros)
        elif ones > 0:
            print("1", end='')
            ones -= 1
            counting_function(target,ones,zeros)

input_str = input("Input string (A-Z): ")
input_int = string_to_int(input_str)+1
target = input_int
ones = 21
zeros = 21
counting_function(target, ones, zeros)
print("")

Since other approaches seem quite inefficient, I've tried to make a time-optimal one. It is clealy O(N) in N bits of encoding, which is big-O optimal.
Hint: try to think of Pascal's triangle for this one (this diagram reveals it)
Sample outputs:
Input:  AAAAAAAA
Output: 000000000000000000000111111111111111111111

Input:  ZZZZZZZZ
Output: 011001000000011010011000111010110110111110

Execution time: < 0.013 s (roughly constant for all inputs)

Here is a quick golfed version(135 bytes, score 135).

@Bubbler Incredible, I did not posses the skills to achieve this

But you should make some effort to minimize your score. All submissions should make a serious effort to optimize the score, otherwise it's invalid.

@user202729 I've modified to Bubbler's version then, which is minimized. I did make an effort to minimize my score though, just not through code size.

About the latter point... correct.

Jelly, 16 bytes
42ɠO%ḅ26ịœcH$ạ‘Ṭ

Uses +,-./0123456789:;<=>?@ABCD for input and returns a list of ones and zeroes.
This attempts to build a list of 538,257,874,440 combinations in memory, so you'll need a large amount of RAM to run it as is...
Try it online! (testable; input length 3, output length 18)
How it works
42ɠO%ḅ26ịœcH$ạ‘Ṭ  Main link. No arguments.

42                Set the argument and the return value to 42.
  ɠ               Read one line from STDIN.
   O              Ordinal; map ['+', ..., 'D'] to [43, ..., 69].
    %             Take the code points modulo 42, mapping [43, ..., 69] to
                  [1, ..., 26].
     ḅ26          Convert the result from base 26 to integer.
            $     Combine the two links to the left into a monadic chain.
           H          Halve; yield 21.
         œc           Generate all 21-combinations of [1, ..., 42].
                  There are 538,257,874,440 of these combinations. The first
                  269,128,937,220 begin with a 1.
        ị         Retrieve the combination at the index to the left.
                  [26, 26, 26, 26, 26, 26, 26, 26] in bijective base 26 equals
                  217,180,147,158 in decimal, so the retrieved combination will
                  begin with a 1.
              ‘   Increment; yield 43.
             ạ    Absolute difference; map [1, ..., 42] to [42, ..., 1].
                  The combination now begins with a 42.
               Ṭ  Untruth; turn the combination into a Boolean list, with 1's
                  at the specified indices and 0's elsewhere.
                  Since the maximum of the combination is 42, this list will have
                  exactly 42 items, 21 of which will be 1's.

Python 3, 75 bytes, Max Diff 0, Length 42, Score 112
lambda s:sorted({*permutations("01"*21)})[int(s,26)]
from itertools import*

Try it online!
This only works in theory because of memory constraints. There are 538257874440 distinct balanced zero-one strings of length 42 and 208827064575 possible inputs, so some of the possible outputs will not be used.
-37 bytes thanks to @recursive

You could use int(s,26) for your index value rather than sum(...) if you change your input character set.

@recursive that would require unprintables. tried that already

Unprintables?  It uses [0-9A-P], doesn't it?  On my machine, int("123ABC",26) == 12855114

@recursive oh yeah you're right idk what I was thinking lol. thanks!

C++, 146 Bytes, 42 maxlength, 0 unbalance, score 146
#include<algorithm>
long long i,s;int f(char*I,char*O){for(O[i=42]=s=0;i--;i<8?s=s*26+I[i]:0)O[i]=i%2|48;for(;s--;)std::next_permutation(O,O+42);}

Works for any continious 26 char, but warning it runs an unacceptable time

It looks like that you're requiring an empty array being passed in addition. I don't think that's valid. / If you are using GCC you can replace #include<algorithm> with #import<regex>.

I'll change it when GCC decide to stop using an given pointer as output

... so that's pointer to output? Looks valid then. But you should mention the input/output format explicitly.

><>, 75 bytes, Max Diff 0, Length 42, score 75
0i:0(?v'A'-$dd+*+!
.")1+.\1+:0$:2%:}:@-2,@+$bl"
[ab+-?\$:?vv~3
~~]>n<v$-1<>

Try it online!
Fair warning, this will take a very very very long time to complete even for the trivial AAAAAAAA case. Runs through each binary representations of a counter until the (base 26 representation of the input)'th binary number with 21 1s is reached. If you want to test the program somewhat you can replace the ab+ on the third line with 1 which will return the nth binary number with just a single 1, Try it online!


text:
There, I fixed it (with tape)
Challenge:
Given a string only containing upper- and/or lowercase letters (whichever you prefer), put tape horizontally to fix it. We do this by checking the difference of two adjacent letters in the alphabet (ignoring wrap-around and only going forward), and filling the space with as much TAPE/tape as we would need.

Example:
Input: abcmnnnopstzra
Output: abcTAPETAPETmnnnopTAstTAPETzra
Why?

Between c and m should be defghijkl (length 9), so we fill this with TAPETAPET;
Between p and s should be qr (length 2), so we fill this with TA;
Between t and z should be uvwxy (length 5), so we fill this with TAPET.

Challenge rules:

The difference only applies forward, so no tape between zra.
It is possible to have multiple of the same adjacent letters like nnn.
You are allowed to take the input in any reasonable format. Can be a single string, string-array/list, character-array/list, etc. Output has the same flexibility.
You are allowed to use lowercase and/or uppercase any way you'd like. This applies both to the input, output, and TAPE.
It is possible no TAPE is necessary, in which case the input remains unchanged.

General rules:

This is code-golf, so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link to a test for your code.
Also, please add an explanation if necessary.

Test cases:
Input:  "abcmnnnopstzra"
Output: "abcTAPETAPETmnnnopTAstTAPETzra"

Input:  "aza"
Output: "aTAPETAPETAPETAPETAPETAPEza"

Input:  "ghijk"
Output: "ghijk"

Input:  "aabbddeeffiiacek"
Output: "aabbTddeeffTAiiaTcTeTAPETk"

Input:  "zyxxccba"
Output: "zyxxccba"

Input:  "abccxxyz"
Output: "abccTAPETAPETAPETAPETAPExxyz"

Input:  "abtapegh"
Output: "abTAPETAPETAPETAPETtaTAPETAPETAPETApeTgh"

Input:  "tape"
Output: "taTAPETAPETAPETApe"

Unsure why we would discard some between fix-ups (e.g. we discard APE after fixing with TAPETAPET and before fixing with TA) seems like a waste of good TAPE to me, but maybe that's just how I roll (sorry).

@JonathanAllan Hehe, you're indeed right that it's kinda a waste of 'tape'. Hmm, could be something I might use in part 2 of the challenge. ;)

What about if the string comes in with tape - e.g., abTAPEgh ?

@manassehkatz It would be interpret as every other character, so ab[TAPETAPETAPETAPET]TA[TAPETAPETAPETA]PE[T]gh (added the [] to make it more readable).

@KevinCruijssen Which is consistent, though (as with the "wasting tape" question) not 100% logical. So maybe one more test case: Input TAPE, output TATAPETAPETAPETAPE (I think I got that right...)

Can i take each character as a separate argument?

@AsoneTuhid Sure, why not. :)

05AB1E, 14 12 bytes
'¡ÉIÇ¥<∍‚ζJJ

Try it online!
Explanation
'¡É            # push the string "tape"
   I           # push input
    Ç          # convert to a list of character codes
     ¥         # calculate deltas
      <        # decrement
       ∍       # extend the string "tape" to each of these sizes
               # results in an empty string for sizes smaller than zero
        ‚ζ     # zip with input (results in a list of pairs)
          JJ   # join to a list of strings and then to a string

Would you mind adding an explanation? I think it's fairly similar to the Jelly answer, but I'm curious which of the characters are used for which of the operations to get the result. One of the general rules in my challenges: "Also, please add an explanation if necessary.", with languages like Jelly, 05AB1E, Charcoal, APL, etc. it's save to assume most people can't read it and an explanation is mandatory. :)

@KevinCruijssen: Certainly. I usually add an explanation to my 05AB1E answers, but I don't always have time right when I post it.

@KevinCruijssen in the arguments of any 05AB1E TIO link you can add -d to get the raw stack operation-by-operation dump of what is going on in lieu of an explanation, but I try to post them too it isn't straightforward especially on some of mine LOL.

Jelly, 13 bytes
OI’“¡ʂƁ»ṁ$€ż@

Try it online!
Explanation

OI’“¡ʂƁ»ṁ$€ż@ – Full program. Take a string as a command line argument.
O             – Ordinal. Get the ASCII values of each character.
 I’           – Get the increments (deltas), and subtract 1 from each.
          €   – For each difference I...
   “¡ʂƁ»ṁ$    – Mold the compressed string "tape" according to these values.
                Basically extends / shortens "tape" to the necessary length.
           ż@ – Interleave with the input.

Here's a trick to get you down to 12

@JonathanAllan That seems invalid to me. It outputs abctapetapetmnnnopapstetapezra instead of abctapetapetmnnnoptasttapetzra.

Oh, yes it's invalid - I had not realised we were to waste tape from the roll!

Haskell, 58 bytes
f(x:y:r)=x:take(length[x..y]-2)(cycle"TAPE")++f(y:r)
f s=s

Try it online! The function f recurses over the string and looks at consecutive characters x and y. cycle"TAPE" yields the infinite string "TAPETAPETAPE...". [x..y] gets the range of characters from x to y inclusive, so we need to subtract two from the length. In case x occurs later in the alphabet then y or both are the same character, we get a negative number after subtracting, but luckily take accepts those as well and just takes nothing.

Perl 5, -F 46 bytes
#/usr/bin/perl -F
use 5.10.0;
say map{((P,E,T,A)x7)[2..-$^H+($^H=ord)],$_}@F

Try it online!

Was about to ask why P,E,T,A instead of T,A,P,E, but I now notice you've used ((P,E,T,A)x7)[2..-$^H+($^H=ord) instead of ((T,A,P,E)x7)[0..-$^H+($^H=ord)-2 to save two bytes. Nice answer!

Very nice indeed! Much better than my naiive approach! You can save 2 bytes using literal ^H (\x08) though!

@DomHastings Literal control character variables have been disabled for quite many perl versions already.  I could claim a score on an older perl version (Like I did recently for do$0) but it's only 2 bytes here, so I didn't bother

Ah, of course! It's because macOS has 5.18.2 by default, so it's the version I'm most familiar with!

Python 2, 96 87 80 bytes
lambda s:''.join(c+(C>c)*('TAPE'*6)[:ord(C)+~ord(c)]for c,C in zip(s,s[1:]+' '))

Try it online!

Haskell, 64 bytes
t="TAPE"++t
e=fromEnum
f(x:y:z)=x:take(e y-e x-1)t++f(y:z)
f x=x

Handles strings of either uppercase or lowercase letters, but not both.
Try it online!

Python 3, 98 bytes
lambda a:"".join(sum(zip(a,[("TAPE"*9)[:y>x and~ord(x)+ord(y)]for x,y in zip(a,a[1:])]),()))+a[-1]

Try it online!
-1 byte thanks to Asone Tuhid

@AsoneTuhid Thanks. I'd recommend posting your own answer because you've golfed off quite a bit and you also golfed TFeld's answer to the same thing so editing would cause dupes (which isn't disallowed)

Alright, have a -1 byte

@AsoneTuhid oh okay, thanks

C, 84 bytes
i,l;f(char*s){for(;*s;)for(putchar(l=*s++),l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}

Try it online!
C (run on Windows Command Prompt), 81 bytes
i,l;f(char*s){for(;putchar(l=*s++);)for(l=s[i=0]+~l;i<l;)putchar("TAPE"[i++%4]);}

Output:

PHP, 85 bytes
$s=str_split($argv[1]);foreach($s as$l)echo str_pad($l,ord(next($s))-ord($l),'TAPE');

Try it online!
Explanation
$s = str_split($argv[1]);   // convert the parameter string to an array
foreach($s as $l)           // loop the array
echo str_pad(               // print
  $l,                       // the letter
  ord(next($s)) - ord($l),  // calculate the distance to the next letter using ASCII values
  'TAPE'                    // padding string
);                          // profit!

Welcome to the site! :)

Scala, 66 bytes
(s:String)=>s./:("z"){(o,c)=>o+("TAPE"*6).take(c-o.last-1)+c}.tail

Try it online!
Explanation
/: foldLeft over the string
("z") starting with a non-empty string to we don't have to handle the first iteration in a special way
"TAPE"*6 generate a long enough string of TAPETAPETA...
.take(c-o.last-1) take the difference between this character and the previous (now the last char in the output so far) characters from the TAPETAPETA... string. o.last will always be safe because we start with a non-empty string.
o+...+c append it to the output so far ... and add this character to the end
.tail get rid of the leading z we added

Welcome to PPCG, and nice first answer! +1 from me.

 Javascript, 131 127 Bytes
4 Bytes saved thanks to  Rick Hitchcock.
z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))

 Unrolled

z=a=>[...a].reduce(
  (x,y)=>
    x + [...Array(
      (f = y.charCodeAt()-(x.slice(-1).charCodeAt()) ) > 1 ? (f-1) : 0
    )].reduce(
      (e,r,t)=>
        e + "TAPE"[t%4],"") + y
);

My Problem here is that Javascript had no clean way to get the distance between character a and b.

  <input id="input-box" type="text">

output

Nice.  You can save a byte by removing the trailing semi-colon, and save a few more bytes by assigning charCodeAt to a variable:  z=(a=>[...a].reduce((x,y)=>x+[...Array((f=y[c='charCodeAt']()-x.slice(-1)[c]())>1?f-1:0)].reduce((e,r,t)=>e+"TAPE"[t%4],"")+y))

Thanks! I'm absolutely disgusted by how that works, but it's good to know that it does for the future.

Python 2 / 3, 70 69 bytes
f=lambda s,*t:t and s+('TAPE'*6)[:max(ord(t[0])+~ord(s),0)]+f(*t)or s

Try it online!

Excel VBA, 106 bytes
An anonymous VBE immediate window function that takes input as an uppercase string via cell A1 and outputs to the VBE immediate window.
a=90:For i=1To[Len(A1)]:c=Mid([A1],i,1):b=Asc(c):For j=2To b-a:?Mid("peta",j Mod 4+1,1);:Next:?c;:a=b:Next

Ruby, 59 53 bytes
->s{s.reduce{|x,y|x+y.rjust(y.ord-x[-1].ord,"TAPE")}}

Try it online!
This is actually pretty straightforward - we take input as split our string into  an array of chars (thanks to Asone Tuhid for pointing this out) and apply reduce operation, where we justify each char to the required length using "TAPE" as filler string.

The question says you can take input as an array of characters. (53 bytes)

JavaScript (ES6), 80 78 bytes
f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s

The distance between two characters can be determined by converting their concatenation to base 36, subtracting 370, modulus 37.
For example, (parseInt('cy',36)-370)%37 == 22.
We can then use padEnd to fill in the gaps, and recursion to handle the loop.
Test Cases:

f=([s,...S],t=S[0])=>t?s.padEnd((t>s)*(parseInt(s+t,36)-370)%37,'TAPE')+f(S):s

console.log(f('abcmnnnopstzra'));
console.log(f('aza'));
console.log(f('ghijk'));
console.log(f('aabbddeeffiiacek'));
console.log(f('zyxxccba'));
console.log(f('abccxxyz'));
console.log(f('abtapegh'));
console.log(f('tape'));

K4, 48 bytes
Solution:
{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}

Examples:
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"abcmnnnopstzra"
"abcTAPETAPETmnnnopTAstTAPETzra"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aza"
"aTAPETAPETAPETAPETAPETAPEza"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"zyxxccba"
"zyxxccba"
q)k){,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"}"aabbddeeffiiacek"
"aabbTddeeffTAiiaTcTeTAPETk"

Explanation:
Fairly simple solution, but a high byte count... Find the deltas, take from the string "TAPE", join to the original string cut where the deltas are > 1.
{,/_[w;x],',[1_d w:&0<d:-1+-':"j"$x;0]#\:"TAPE"} / the solution
{                                              } / lambda
                                         "TAPE"  / the string TAPE
                                      #\:        / take each-left
           ,[                      ; ]           / join (,)
                                   0             / zero (ie append zero)
                              "j"$x              / cast input to int
                           -':                   / deltas
                        -1+                      / subtract 1
                      d:                         / assign to d
                    0<                           / delta greater than 0?
                   &                             / indices where true
                 w:                              / assign to w
               d                                 / index into deltas at w
             1_                                  / drop first
         ,'                                      / join each-both
   _[w;x]                                        / cut input x at indices w
 ,/                                              / flatten

Charcoal, 20 bytes
⭆θ⁺…TAPE∧κ⊖⁻℅ι℅§θ⊖κι

Try it online! Explanation:
 θ              θ       Input string
⭆                       Map over characters
                  κ     Current index
                 ⊖      Decremented
               §        Index into string
             ι          Current character
            ℅ ℅         Ordinal
           ⁻            Subtract
          ⊖             Decremented
         κ              Current index
        ∧               Logical and
    TAPE                Literal string
   …                    Mold to length
                   ι    Current character
  ⁺                     Concatenate
                        Implicitly print

Java (JDK), 91 bytes
s->{var p='z';for(var c:s)System.out.print("ETAP".repeat(9).substring(1,c>p?c-p:1)+(p=c));}

Try it online!
Explanation
s->{                       // char[]-accepting lambda consumer, printing a String
 var p='z';                //  store the previous character
 for(var c:s){             //  for each character of the string
  System.out.print(        //   print...
   "ETAP".repeat(9)        //    "ETAP" repeated 9 times (to go above 26 chars)
    .substring(1,          //     of which, we substring c-p -1 characters
     c>p?c-p:1             //
    )                      //
   +(p=c)                  //    and append c, while also storing the previous character
  );

Credits

-2 bytes thanks to R.M
-4 bytes thanks to ceilingcat, by upgrading to Java 10+ and switching types to var
-3 bytes thanks to Kevin Cruijssen, by printing the result of my (previously) alternate version instead of returning it

int p=123 would save one character. It doesn't matter what p is in the first iteration, as long as it is larger than or equal to the first character. The largest value the first character can have is 'z' == ASCII 122, so 123 is good enough. Also, if you used capital letters, you could use 91 instead of 123, saving another character.

@R.M Thanks, indeed that works!

-3 bytes by printing directly in your alternative method.

Ruby, 78 77 64 62 bytes
-1 byte thanks to Kevin Cruijssen
f=->s,*t{t[0]?s+('TAPE'*6)[0,[0,t[0].ord+~s.ord].max]+f[*t]:s}

Try it online!

You can save a byte changing ord-l[-1].ord-1 to ord+~l[-1].ord. Nice answer, though. +1 from me.

Pip, 29 bytes
O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa

Takes input as a command-line argument (lower- or uppercase, doesn't matter).
 Try it online!
Explanation
O@a{"TAPE"@<MX[0v-$-Ag]}.BMPa
                               a is 1st cmdline arg; v is -1 (implicit)
O                              Output without newline
 @a                            the first character of a
                          MPa  Map this function to pairs of successive characters of a:
                    Ag          Get the ASCII codes of the two characters
                  $-            Fold on subtraction (i.e. asc(first)-asc(second))
                v-              -1 minus the above (i.e. asc(second)-asc(first)-1)
              [0      ]         A list containing 0 and the above
            MX                  Max of the list
          @<                    The first ^ characters (with cyclic indexing)
    "TAPE"                      of this string
   {                   }.B      Concatenate the second character

APL (Dyalog Classic), 30 bytes
{∊⍵,¨⍨⍴∘'TAPE'¨0,0⌈-1+2-/⎕a⍳⍵}

Try it online!
{ } anonymous function with argument ⍵
⎕a⍳⍵ find indices of its chars in the alphabet
2-/ pairwise differences (prev minus next)
1+ add 1
- negate
0⌈ max(0, ...)
0, prepend a 0
⍴∘'TAPE'¨ reshape cyclically the string 'TAPE' to each
⍵,¨⍨ append each char from the argument to the corresponding reshaped string
∊ flatten

K (oK), 33 bytes
{,/((0|-1+0,1_-':x)#\:"TAPE"),'x}

Try it online!
{ } anonymous function with argument x
-':x subtract each prior (use an imaginary 0 before the first item)
1_ drop first item
0, prepend a 0
-1+ add -1
0| max(0, ...)
(...)#\:"TAPE" reshape the string "TAPE" to each item from the list on the left
(...),'x append the corresponding character from x to each reshaped string
,/ concatenate all

Yabasic, 119 bytes
An anonymous function that takes input as an uppercase string and outputs to STDOUT.
Input""s$
a=90
For i=1To Len(s$)
c$=Mid$(s$,i,1)
b=Asc(c$)
For j=2To b-a
?Mid$("peta",Mod(j,4)+1,1);
Next
?c$;
a=b
Next

Try it online!

Clojure, 139 119 bytes
#(reduce-kv(fn[r x c](let[a(cycle "TAPE")i int d(-(i(nth(cycle %)(inc x)))(i c))](str r(if(> d 1)(apply str c(take(dec d)a))c))))""(vec %))

Anonymous function which take the string and returns the taped one. As always, Clojure doesn't seem to perform all too well. What I couldn't really work out is fetching the next char in a short way. On the last char I would get an OutOfBoundsException, reason obvious. So I put a cycle around it. Maybe there is a more elegant solution.
Ungolfed
#(reduce-kv
  (fn [r x c]
    (let [a (cycle "TAPE")
          i int
          d (-
             (i (nth (cycle %) (inc x)))
             (i c))]
      (str r
           (if (> d 1)
             (apply str c (take (dec d) a))
             c))))
  ""
  (vec %))

Update
Managed to shafe off a few bytes. Got rid of the pesky if statement by decrementing the difference. take produces an empty list if the number is 0 or less which in turn results in an empty string.
#(reduce-kv(fn[r x c](let[d(-(int(nth(cycle %)(inc x)))(int c)1)](str r c(apply str(take d(cycle "TAPE"))))))""(vec %))

Ungolfed
#(reduce-kv
  (fn [r x c]
    (let [d (-
             (int (nth (cycle %) (inc x)))
             (int c)
             1)]
      (str
       r
       c
       (apply
        str
        (take
         d
         (cycle "TAPE"))))))
  ""
  (vec %))

C# (.NET Core), 122 111 bytes
Saved 11 bytes thanks to @KevinCruijssen
s=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;)r+="ETAP"[(e-d)%4];return r;}

Try it online!
Explanation:
s =>
{
    var r = "" + s[0];                  //Declare string for the result and initialize with the first character from the input.
    for (                               //Loop over the input,
        int i = 1, e, d;                //starting with the second character, also declare helper variables.
        i < s.Length;                   //Loop until the end of the input is reached.
        r += s[i++])                    //Add the current character to the result and increase the counter.
        for (                           //Loop for adding the TAPE.
            e = d = s[i] - s[i - 1];    //Calculate the differnce between the current and the previous character.
            d-- > 1;)                   //Loop until the difference is 1.
            r += "ETAP"[(e - d) % 4];   //Add a character from the TAPE to the result.
    return r;                           //Return the result.
}

Nice answer, +1 from me. You can save 4 bytes by changing the while to a for and removing the brackets: for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;r+=t[(e-d)%4]);. :) Oh, and since you're using t="ETAP" only once, you can use it directly, and change string to var to save 7 more bytes: s=>{var r=""+s[0];for(int i=1,e,d;i<s.Length;r+=s[i++])for(e=d=s[i]-s[i-1];d-->1;r+="ETAP"[(e-d)%4]);return r;}.

@KevinCruijssen: Thanks, I wouldn't have thought about getting rid of the brackets by moving the stuff to the for loop. Also if feel stupid for missing that I can use "ETAP" directly.

Your answer is still great, so don't worry about it. :) I get golf-tips almost every time I post an answer myself.. And it's also easier to golf an existing answer further than having it completely golfed right from the start. PS: you might have already seen them, but Tips for code-golfing in C# and Tips for golfing in  might be interesting to read through if you haven't yet.

Python 3, 90 bytes
p,o=' ',''
for t in input():y=(ord(t)-ord(p)-1)*(p!=' ');o+=('TAPE'*y)[0:y]+t;p=t
print(o)

Try it Online

Hi, I've fixed your title from **title** to #title. Also, would you mind adding a TryItOnline-link with test code?

CJam, 27 25 bytes
q_:i2ew.{:-~0e>_"TAPE"*<}

Try it online!
Far, far from the other golfing languages, but I'm proud of this golf anyway.
Explanation
q                            Read the input
     ew                      And take windows of size
    2                          2
   i                           from the code points
  :                            of each of its characters.
        {               }    For each of these windows:
         :                     Reduce with
          -                      subtraction.
                                 Since there are only 2 elements, this just subtracts them.
             e>                Take the maximum
           ~                     of this difference's bitwise negation
            0                    and zero.
                                 This returns -n-1 if n is negative, and 0 otherwise.
                                 Call this new value m.
                      *        Repeat
                "TAPE"           the string "TAPE" m times.
               _       <       And then take the first m elements.
                             The result of this will be an array of strings which consist of
                             the string "TAPE" repeated the proper amount of times.
       .                     Zip this array with the original input.
                             Since the original input is one element longer than this array,
                             the nothing is pushed after the final character.
                             Implicitly print everything.

Husk, 26 25 bytes
ΣSoż+C1(moo↑¢¨tȦ9¨>0←Ẋ-mc

Try it online!

PowerShell, 72 bytes
-join($args|% t*y|%{for(;$p*(++$p-lt$_)){'TAPE'[$i++%4]}$i=0;$p=+$_;$_})

Try it online!

Java , 213 166 153 bytes
i->{String o="";for(int a=0,l=i.length;++a<=l;){char u=i[a-1],n;o+=u;if(a<l){n=i[a];o+="TAPETAPETAPETAPETAPETAPET".substring(0,n-u>0?n+~u:0);}}return o;}

try it online
    String o = "";
    for (int a = 0, l = i.length; ++a <= l; ) {              // for each character
        char u = i[a - 1];                                    //  current character
        o += u;                                               //  add current character to output string
        if (a < l) {                                          //  if it's not the last one
            char n = i[a];                                    //  next character
            o += "TAPETAPETAPETAPETAPETAPET".substring(0, n - u > 0 ? n +~ u : 0); // fill with enough tape but only forward
        }
    }
    return o;

Please help me make it better.
Thanks to @cairdcoinheringaahing for the tip on whitespaces.
Thanks to @R.M  for the tip on tape string.
Thanks to @KevinCruijssen  for the lambda and expressions tips.

Welcome to the site! You can remove a lot of whitespace to golf this answer and make sure to check these tips for golfing in Java!

You don't need to create the variable t, because you're only using it once. You can just do "TAPETAPETAPETAPETAPETAPET".substring....

Welcome to PPCG! In addition to what @R.M said, you can golf a few more things: int a=1,l=i.length;a<=l;a++ can be int a=0,l=i.length;++a<=l;, char u=i[a-1];o+=u;if(a<l){char n= can be char u=i[a-1],n;o+=u;if(a<l){n=, (n-u) doesn't need the parenthesis, and n-u-1 can be n+~u. Also, your answer is currently a snippet instead of a function. To make it a lambda you'll need to add i->{ in front and } at the end. So in total: Try it online. 153 bytes

140 bytes


text:
Compress to Impress
Inspired by both the challenge "Unique is Cheap" by @Laikoni, where the score is based on the challenge itself, as well as the JavaScript (ES6) answer of @ETHproductions for the "Palindrome Compression" challenge, where he uses a pretty cool compression method for the palindrome-flag, upper/lower case indication, and letters.
Challenge:
You will create two programs/function: a compress program/function, and a decompress program/function.
Compress program/function:
Given the characters used in your own source code (both the compress and decompress source code combined) as only possible input, use any kind of bit-compression method of your choice and output the resulting 0s and 1s of the bit-compression of this input.
The amount of bits (0s and 1s) outputted must be as short as possible, and this amount will be the score of your answer.
The idea is to have a nice balance between the different kind of characters used in your own source code, the size of your programs/functions, and the type of bit-compression you've used. Or to quote @RobertFraser in this comment:

This is a great example of the fundamentals of engineering. Taking a problem description, thinking about different ways to solve it, and making tradeoffs between requirements (ie how many bits to dedicate to various styles), etc

Challenge rules:

The compressor and decompressor program/function should be in the same programming language.
You must provide both a compression and decompression program/function, and the amount of 0s and 1s your compression program outputs for both programs/functions combined (concatted) as input will be your score.
The compression must - obviously - work for all characters used in your source code of both your compression and decompression program/function, in any order or amount. (It can have undefined behavior for any characters not in your source code.)
Input-type doesn't necessarily have to be a string. It could also be a list/array/stream of characters, and it can be as program argument, STDIN, etc. Your call.
Same applies to the output. Can be returned from a function or printed to STDOUT. Can be a single string, integer-array, etc.
Your compression program must output at least one 0 or 1 (so an empty cat program for both the compression and decompression program isn't possible).
Your source code may not only contain 0s and 1s already, excluding no-ops (to prevent programming languages that print their own source code by default, where both the compression and decompression programs can be a single 0 or 1, and the no-ops part is to prevent this behavior with an unused comment; sorry binary-based programming languages which only use 0s and 1s as source code).
Although you'll have to support an input of 0 or more of the character-pool used in your programs/functions, you don't have to support an empty input. So you can assume every input will be at least 1 character.
A possible input can be larger than your compression and decompression sizes combined.
If for whatever reason your compression method is order-depended and has a shorter output when your input is DecompressionProgramCompressionProgram instead of CompressionProgramDecompressionProgram, you are allowed to choose either order of concatting of your programs/function for your score.

Example:
Let's say the compression program is ABC, and the decompression program is 123aBc. For any input containing zero or more of the character-pool 123ABCab, it should be able to correctly compress those characters to 0s and 1s, and be able to decompress these 0s and 1s back into the correct characters. Some valid example inputs for these two programs can be: ABC123aBc (of course); A; 1Ca; 22222b1121221b; etc.
General rules:

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Example of an answer:

Java 8, score 1440 bits, 180 (87 + 93) bytes
Here a very bad implementation in Java 8, where each character is simply printed as 8-bit binary String.
Compression function:
Input provided as java.util.stream.IntStream.
s->s.forEach(c->System.out.print("".format("%8s",Long.toString(c,2)).replace(' ','0')))

Try it online.
Decompression function:
Input provided as String.
s->{for(Integer i=0;i<s.length();System.out.printf("%c",i.parseInt(s.substring(i,i+=8),2)));}

Try it online.

This is not a quine test, so can I read my source code?

@WeijunZhou Depends on what you use it for, but I probably allow it in most cases. I guess you want to read your source code and then map easy of it's characters with a look-up table, or something like that?

Yes, something similar is on my mind.

I may have missed something, but here's a possible loophole in the rules: compressor->if input==compr_code+decompr_code then return 0 else return binary charcodes of input, decompressor->if input==0 then return compr_code+decompr_code else convert binary codes to characters and return them. Final score: 1 (lowest possible). The programs won't be trivial to write, but with some tricks from quines they surely are doable.

@Leo Hmm, you're indeed right that the current rules allow such an answer (unintentionally of course). Not sure how to fix it, though.. I could state you must provide the mapping you've used for each individual character, which must correspond / be the same for the compressor + decompressor input as well as any random configuration of these characters. But in that case I might limit possible answers who want to compress pairs of characters, or whatever they come up with. Any suggestions on a rule to close this loop hole, but still leave some flexibility for creativity?..

One possibility is requiring that adding a character to any input should increase the length of the compressed output by no more than 8 bits. But beware that even this change could invalidate some "honest" answers

Jelly, score 350, 39 + 30 = 69 bytes
Compressor: Jelly, 39 bytes
“iÐ€;⁴⁾¤8Bz0ZUṖFs5Ḅị”;⁾“”¤iÐ€;⁴BUz0ZUṖF

Try it online!
Decompressor: Jelly, 30 bytes
s5Ḅị“iÐ€;⁴⁾¤8Bz0ZUṖFs5Ḅị”;⁾“”¤

Try it online!

@KevinCruijssen whoops. fixed, thanks

@KevinCruijssen oh I'm bad lol. thanks for the fix!

Java (OpenJDK 9), score 702 bits, 88 (42 + 46) bytes
Compressor, 42 bytes
$->new java.math.BigInteger($).toString(2)

Try it online!
Decompressor, 46 bytes
$->new java.math.BigInteger($,2).toByteArray()

Try it online!

Sorry, I'm playing the low byte-cost (hum, for Java, I mean) rather than the hard compression :S

Didn't even knew it was possible to put any String in the BigInteger constructor.. Figured it would give a NumberFormatException or something.. I did knew about the .toString(2). Nice golf of my example answer I guess. ;)

@KevinCruijssen Indeed, as it currently is, it's more a golf of your example than anything else. 703 bits means 88 bytes. I couldn't compress anything in less than 88 bytes so far, but I'm still trying to ;-)

Pyt, score 179 bits, 9+10=19 bytes
Compressor:
←6!58*-Ĩɓ

Try it online!
Decompressor:
←2Ĩ6!58*-Ṕ

Try it online!

Decompressor still seems to throw an error

That's strange. It works when I run it locally.