text:
Random triple with uniform marginals
Output a random triple \$(x,y,z)\$ of real numbers such that

\$x+y+z=\frac{3}{2}\$
Each of \$x,y,z\$, taken alone, is uniformly distributed from \$0\$ to \$1\$.

Please explain in your answer what distribution your code produces and why it meets these conditions. In particular, please include a demonstration that with many samples produced by running your code many times, the distribution of each variable alone is approximately uniform.
Allowances for precision
Since computers can't produce actual real numbers, you can approximate them by outputting any of:

Floats
Decimals
Rationals

I've tried to make the rules here as friendly as possible.
Your outputs need to be accurate within \$\pm 10^{-3}\$, that is 3 decimal digits. That means you can imagine that each real-number output from your true distribution has been fudged by at most \$\pm 10^{-3}\$ in any way. It's fine if this makes \$x+y+z\$ be a bit off from \$\frac{3}{2}\$.
You may output rationals as (numerator, denominator) pairs of integers or similar. You may also choose to output just one denominator that applies to all three values, that is, output \$a,b,c\$ and \$d\$ to represent \$\frac{a}{d},\frac{b}{d},\frac{c}{d}\$. Rationals don't have to be in reduced form.
Randomness
You can assume any standard PRNG is in fact random. For instance, if it outputs random floats from 0 to 1, you can assume these are uniformly random reals that are independent from each other, and not worry about any endpoint issues. It's also fine if your code fails in a probability-zero event.
To decide whether a pseudo-random source such as time or memory contents is sufficiently random, consider an empirical test where your code is run many times in sequence to check if the randomness varies sufficiently between runs. You may have these runs be done within your language such as in a loop, or by repeatedly calling the code from outside like with a shell command. You may not assume any intentional time delay or other actions taken between runs.

Related, basically the same except that the distribution is $(-1,1)$ and the equation is $ x^2 + y^2 + z^2 = 1$

@ChasBrown I think what Jo King is referring to is the interesting property of the uniform distribution on the sphere that each of its coordinates alone has the uniform distribution.

Perhaps more closely related?

can we output 3 ints between 0 and 1000 whose sum is 1500?

@ngn Yes, except you need to also need to output the number 1000 as per the rationals option with one denominator.

@xnor: In Re uniform points on a sphere: Well, I'll be darned - it is uniformly distributed on the interval for each axis!

Is the range $(0,1)$ or are we also allowed to use a range $(0,1]$ instead (i.e. is [1.000, 0.100, 0.400] a valid output)?

@KevinCruijssen Any way of treating endpoints is fine.

APL (Dyalog Unicode), 15 bytesSBCS
1|(-,.5∘-,+⍨)?0

Try it online!
A full program that generates three floating-point numbers \$ X,Y,Z \$.
The distribution
Uses the same method as Luis Mendo's MATL answer, which in turn is from this Math.SE answer. The Math.SE answer presents the following random variables:
$$
X = \text{uniform random value in } (0,1) \\
Y = \begin{cases} X + \frac12, \quad X < \frac12 \\
X - \frac12, \quad X \geq \frac12 \end{cases} \\
Z = \frac32 - (X + Y)
$$
I found that this is equivalent to
$$
X = \text{uniform random value in } (0,1) \\
Y = \{ X + 1/2 \}, Z = \{-2X\}
$$
which, in turn, has the same distribution with
$$
r = \text{uniform random value in } (0,1) \\
X = \{ -r \}, Y = \{ 1/2 - r \}, Z = \{ 2r \}
$$
where the notation \$ \{ x \} \$ means the positive fractional part of \$ x \$.
How the code works
1|(-,.5∘-,+⍨)?0
             ?0  ⍝ r←Generate a random number from (0,1)
  ( ,    ,  )    ⍝ Create a 3-element array from r:
   -             ⍝ -r
     .5∘-        ⍝ 0.5 - r
          +⍨     ⍝ r + r (= 2r)
1|               ⍝ Extract positive fractional part from each number

Test script
⍝ Take 10000 samples of X, Y, Z's
data←f¨⍳10000

⍝ Tests that X+Y+Z = 1.5 in all cases
∧/1.5=+/¨data

⍝ Shows the distribution of X,Y,Z in 10 bins
{(⊂∘⍋⌷⊢)↓,∘≢⌸⍵}¨⌊10×↓⍉↑data
                    ↓⍉↑data  ⍝ Reform the data into X's, Y's, and Z's
                ⌊10×         ⍝ Classify into 10 bins
{             }¨     ⍝ For each of X's, Y's, or Z's,
        ↓,∘≢⌸⍵       ⍝ Gather the list of (bin, count)
 (⊂∘⍋⌷⊢)             ⍝ Sort the bins

⍝ Example result
X:  0 1012  1 1016  2 993   3 1025  4 1002  5 969   6 1002  7 977  8 1049  9 955
Y:  0 969   1 1002  2 977   3 1049  4 955   5 1012  6 1016  7 993  8 1025  9 1002
Z:  0 1013  1 944   2 1022  3 1052  4 990   5 980   6 1039  7 979  8 959   9 1022

Alternative method, 21 bytesSBCS
(3*9),3⊥¨3|(⍳3)+⊂?9/3

Try it online!
This one uses the OP's formulation from the same Math.SE question:

Generate a uniform random number \$ X \$ from \$ (0, 1) \$.
Take its ternary digits \$ X = 0.X_1 X_2 X_3 \cdots \$ and generate ternary digits of \$ Y \$ and \$ Z \$:

$$
Y_i = (X_i + 1) \% 3 \\
Z_i = (X_i + 2) \% 3
$$

Then the resulting numbers \$ X,Y,Z \$ are uniform in range \$ (0, 1) \$, and their sum is

$$
\frac3{3^1} + \frac3{3^2} + \frac3{3^3} + \cdots = \frac32
$$
Theoretically it requires infinite number of digits; the code approximates the scheme with just 9 digits, which makes \$ X+Y+Z=1.499923792 \$. I'm not exactly sure if it meets the OP's spec though.
How the code works
(3*9),3⊥¨3|(⍳3)+⊂?9/3
                 ?9/3  ⍝ Generate 9 ternary digits
         3|(⍳3)+⊂      ⍝ Ternary digits for X,Y,Z
      3⊥¨  ⍝ Convert each list of digits to numerator for the fraction
(3*9),     ⍝ Prepend the denominator

Truncating digits is fine -- the sum of 1.5 can be approximate as well.

You may want to clarify that {...} means fractional part; I had to see the code to find out

MATL, 18 17 11 bytes
rt.5+yE_v1\

The code is based on this method, and incorporates Bubbler's improvement, which saved 6 bytes.
Try it online! Or see the three marginal histograms for 1000 realizations, using 10 bins on the interval (0,1).
Commented code
r       % Push random number, r, uniformly distributed on (0,1)
t.5+    % Duplicate, add 0.5. Gives r+0.5
yE_     % Duplicate from below, multiply by 2, negate. Gives -2*r
v       % Concatenate the three values into a column vector
1\      % Modulo 1. Implicit display

Wolfram Language (Mathematica), 51 48 bytes
(.5+Sqrt[3/8]*(#-Mean@#))&@RandomPoint@Sphere[]

Try it online!
Theory
According to this post on MathOverflow about a cool unsolved problem, referencing this other post also on MathOverflow about distributions with nice projections, the following procedure should provide a distribution satisfying the demands of this question:

Pick a random point on a sphere.
Project (orthogonally) to a fixed plane.  The support of the distribution is now a disc, but with a non-uniform distribution.
Inscribe this disc in an equilateral triangle. Take the barycentric coordinates of our projected random point within this equilateral triangle.
These three coordinates now sum to a constant and have a uniform distribution on their support.  Rescale if necessary.

The proof that this works fundamentally comes down to Archimedes's "Hat-Box" Theorem, which is the assertion that a single coordinate of a random point on a sphere has a uniform distribution on its support.
In the solution above, I use the plane x+y+z=0 because it's easy to project to it by subtracting off the mean (one-third of the total x+y+z) from each coordinate.  Then I simply need to shift and scale appropriately (I can even skip the barycentric coordinates, which are themselves just a shift and scale here), which a bit annoyingly involves Sqrt[3/8].  Perhaps I can save a few bytes by taking an approximate value to the tolerances of the original question.
However, I hope that this answer -- or variants of it -- might be efficient to express in some language.
Practice
You can run a Kolmogorov-Smirnov test to see if the distribution is correct.  Try it online to compare the distribution of the first coordinate of this answer (which has the same distribution as the other two coordinates) with the uniform distribution.  Put briefly, we want the result of this test to not be too "close to 0" ("statistically significant").
Remarks
Fun fact: if you scale the coordinates so that their sum is 1, this can be used to solve a nice problem from the xkcd forums.

Two generals, who each control the same number of units, each secretly
  decide how to split their units among three battle fronts. Whoever
  sends more units to a front wins that front, and whoever wins 2 out of
  3 fronts wins overall. Margins of victory are irrelevant. What is the
  optimal strategy , pure or mixed?

Nice connections! Another fun fact: I was the poster of the puzzle you quote from the xkcd forums many years ago!

JavaScript (ES6), 38 bytes
Also derived from this method from math.SE used by Luis.
_=>[x=Math.random(),(x+.5)%1,--x*-2%1]

Try it online!
How?

We pick a uniform random value \$x \in [0,1[\$
We define \$Y=x+\dfrac{1}{2}\$
We define \$Z=2-2x=-2(x-1)\$

Then we define:
$$y=\cases{
Y&\text{if $Y<1$}\\
Y-1&\text{if $Y\ge 1$}
}$$
and:
$$z=\cases{
Z&\text{if $Z<1$}\\
Z-1&\text{if $Z\ge 1$}
}$$
Which can also be written as \$y=Y-d\$ and \$z=Z-(1-d)\$ with:
$$d=\cases{
0&\text{if $x<1/2$}\\
1&\text{if $x\ge1/2$}
}$$
Leading to:
$$x+y+z=x+\left(x+\dfrac{1}{2}-d\right)+(2-2x-(1-d))=\dfrac{3}{2}$$

R, 38 27 bytes
-10 bytes thanks to Nick Kennedy's suggestion of following Bubbler's trick; -1 extra byte by switching \$X\$ to \$1-X\$.
c(x<-runif(1),.5+x,-2*x)%%1

Try it online!
The footer on TIO includes a Kolmogorov-Smirnov test of uniformity for the three marginals.
Equivalent to the easier to read:
R, 38 bytes
c(x<-runif(1),y<-1-2*x+(x>.5),1.5-x-y)

Try it online!
This uses the same method as other answers, rediscovered independently.
Defines \$X\sim U(0,1)\quad
Y = \begin{cases}1-2X\text{ if }X<\frac12\\2-2X\text{ if } X\geq\frac12\end{cases}\quad
Z=\frac32 - X - Y\$
This way:

\$X\sim U(0,1)\$ by definition
\$Y|X<\frac12\$ and \$Y|X\geq\frac12\$ are both \$U(0,1)\$, hence \$Y\sim U(0,1)\$
\$X+Y|X<\frac12 = 1-X|X<\frac12\sim U(\frac12, 1)\$ and \$X+Y|X\geq\frac12 = 2-X|X\geq\frac12\sim U(1, \frac32)\$ hence \$X+Y\sim U(\frac12, \frac32)\$ and therefore \$Z\sim U(0,1)\$

Alternative method: R, 84 bytes
This is much longer, but uses a very different method so I am also posting it (with thanks to Amic Frouvelle).
`?`=runif
x=?1
y=?1
if(abs(x+y-1)>.5|(y>.5)!=(x>.5)&abs(x-y)<.5)y=1-y
c(x,y,1.5-x-y)

Try it online!
Samples \$(X,Y)\$ from the uniform distribution over this shape:

then lets \$Z=\frac32-X-Y\$. These histograms show that the marginals are uniform:

A more direct implementation of Bubbler’s method is shorter ‘c(-(x=runif(1)),.5-x,2*x)%%1` at 28 bytes.

@NickKennedy Thanks! Got it down to 27 by switching between x and -x.

C++ (clang), 206 ... 163 160 bytes
#import<random>
std::vector<double>f(){std::random_device r;std::mt19937 g(r());auto x=std::generate_canonical<double,53>(g),y=x+(x<.5)-.5;return{x,y,1.5-x-y};}

Try it online!
Uses the C++ library's Mersenne twister engine to generate uniform random numbers with \$53\$ bits of randomness in \$[0,1)\$.
I realise we only need to be accurate within \$3\$ decimal digits, but that's going to be at least \$10\$ bits so might as well go the whole hog with \$53\$ (the number of bits in the mantissa part of a double).
Also uses @Bubbler's method to calculate \$(x, y, z)\$.
Ungolfed:
#include <random>
#include <vector>

std::vector<double> f() {
    std::random_device rand_dev;
    std::mt19937 generator(rand_dev());
    double x = std::generate_canonical<double, numeric_limits<double>::digits>(generator);
    double y = x;
    if (y < 1./2) {
        y += 1./2;
    } else {
        y -= 1./2;
    }
    double z = 3./2 - x - y;
    return {x, y, z};
}

Wolfram Language (Mathematica), 79 bytes
Sqrt[1-r[]^2]{Sin@#,Cos@#}.{{1,1,-2},Sqrt@3{1,-1,0}}/4&[2Pi(r=RandomReal)[]]+.5

Try it online!
A bit longer but using the direct Sqrt[1-r^2] distribution on the 2D disc, then rotating and translating the disc into 3D.

05AB1E, 14 17 bytes
₄L¨₄/Ωx¦1αsD.5+¦)

Port of @Bubbler's approach, so make sure to upvote him!
Try it online.
This approach uses random integers in the range \$(0,1)\$.
The footer of the TIOs (=O,) is to verify the result equals 1.5, which will = (print without popping); O (sum); , (pop and print).
Explanation:
₄L            # Push a list in the range [1,1000]
  ¨           # Remove the last value to make the range [1,1000)
   ₄/         # Divide each value by 1000 to make the range [0.001,1) in increments of 0.001
     Ω        # Pop and push a random value of this list
              # (NOTE: 05AB1E doesn't have a random builtin within the range [0,1))
      x       # Double this value without popping
       ¦      # Remove the first digit (the integer portion)
        1α    # And take the absolute difference with 1
      s       # Swap to take the original random value again
       D      # Duplicate it
        .5+   # Add 0.5 to it
           ¦  # And remove the first digit (the integer portion)
            ) # Then wrap all (three) values on the stack into a list
              # (after which this list is output implicitly as result)

₄L₄/3ãʒO3;α_}Ω

Try it online (way too slow for TIO, so will use \$10^{-1}\$ accuracy instead of \$10^{-3}\$ by replacing the ₄s (1000) with Ts (10)).
This approach uses random integers in the range \$(0,1]\$.
This previous 14 bytes answer above unfortunately didn't had marginal distribution. The \$x,y\$ values had the same distribution, but the \$z\$ values were always slightly larger in terms of marginal distribution. Here for example the distribution for the \$x,y,z\$ values with steps of \$0.1\$. These total values will be larger for the actual steps of \$0.001\$ of course, but the \$x,y\$ values will always be the same, and \$z\$ unfortunately always slightly larger.
₄L            # Push a list in the range [1,1000]
  ₄/          # Divide each value by 1000 to make the range [0.001,1] in increments of 0.001
    3ã        # Cartesian product of 3, to create all possible triplets of these values
      ʒ       # Filter these triplets by:
       O      #  Sum the three values
        3;α   #  Take the absolute difference with 3/2
           _  #  And check if it's equal to 0
      }Ω      # After the filter: pop and push a random triplet from this filtered list
              # (which is output implicitly as result)

Are you sure the first method gives the right marginal distributions?

@xnor Hmm, I guess not. Summing all possible $x,y,z$ values gives approximately $[34,34,35.5]$ for the steps of $0.1$. For the steps of $0.001$ these values will be higher, but the $x,y$ will be the same, and $z$ will always be little over 4% larger. So you're indeed correct, the $z$ value doesn't follow the correct marginal distribution. :(

Ruby, 25 bytes
p x=rand,(x+0.5)%1,-2*x%1

Try it online!
Based on the same method as most other answers.

Jelly, 12 bytes
ȷX÷¤._;Ḥ;N%1

Try it online!
A niladic link that returns a list of 3 floats, accurate to within \$\pm 10^{-3}\$, that is 3 decimal digits, and summing to 1.5. Footer demonstrates the sum.
Uses the same method developed by Bubbler.

Perl 5, 50 bytes
$x=rand;$f=$x<.5;say for$x,$x-.5+$f,3/2-2*$x+.5-$f

Try it online!
This answer takes seriously the first word of the question: output (as a verb). Many other answers here moves the output part outside of the byte count :-)


text:
Is this quadrilateral tangential?
Related: Is this quadrilateral cyclic?
Background
A tangential quadrilateral is a quadrilateral which has an incircle:

Examples include any square, rhombus, or a kite-like shape. Rectangles or parallelograms in general are not tangential.
Task
Given the four vertices of a quadrilateral (as Cartesian coordinates), determine if it is tangential.
Input & output
For input, it is allowed to use any format that unambiguously specifies the four vertices' coordinates (eight real or floating-point numbers). You can assume the following on the input:

The points specify a simple convex quadrilateral, i.e. all internal angles are strictly less than 180 degrees, and the edges meet only at the vertices.
The points are specified in counter-clockwise order (or the other way around if you want).

For output, you can use one of the following:

Truthy/falsy values as defined by your language of choice (swapping the two is allowed), or
Two consistent values for true/false respectively.

It is acceptable if your code produces wrong output due to floating-point inaccuracies.
Test cases
Tangential
(0, 0), (0, 1), (1, 1), (1, 0)  # unit square
(-2, 0), (0, 1), (2, 0), (0, -1)  # rhombus
(1, -2), (-2, -1), (-1, 2), (4, 2)  # kite
(0, 0), (50, 120), (50, 0), (32, -24)  # all four sides different

Not tangential
(0, 0), (0, 1), (2, 1), (2, 0)  # rectangle
(0, 0), (1, 1), (3, 1), (2, 0)  # parallelogram

Scoring & winning criterion
Standard code-golf rules apply. The shortest code in bytes wins.

Is complex number input allowed?

@xnor Yes, it's allowed.

MATL, 11 10 bytes
5:)d|2e!sd

Input is a vector of four complex numbers. Output is 0 (which is falsy) if tangential, or nonzero (which is truthy) if not tangential.
Try it online! Or verify all test cases.
Explanation
The code computes the difference between sums of lengths of opposite sides. This difference is zero if and only if the quatrilateral is tangential.
5:   % Range [1 2 3 4 5]
)    % Implicit input: complex vector of length 4. Index into it modularly.
     % This repeats the first vertex after the last
d    % Consecutive differences
|    % Absolute value, element-wise
2e   % Reshape as a 2-column matrix, in column-major order
!    % Transpose
s    % Sum of each column. Gives a vector of length 2
d    % Consecutive difference

Python 3, 89 \$\cdots\$ 59 55 bytes
lambda l:sum((-1)**i*abs(l[i-1]-l[i])for i in range(4))

Try it online!
A list of vertices as complex numbers is passed in. The lengths of the sides \$(a, b, c, d)\$ are calculated and uses \$a+c=b+d\$ for a tangential quadrilateral. Returns's a falsy value (0) for a tangential or a truthy value (nonzero) otherwise.

Python 3, 47 bytes
f=lambda l,i=3:i+1and abs(l[i]-l[i-1])-f(l,i-1)

Try it online!
Take complex number input. Outputs as Truthy/Falsey swapped. Test cases from Noodle9.

48 bytes
lambda a,b,c,d:A(a-b)+A(c-d)-A(b-c)-A(d-a)
A=abs

Try it online!

Jelly, 9 8 bytes
ṁ5ạƝŒœ§E

Try it online!
Explanation
5ị€       | Modular index 1,2,3,4,5 into list
   ạƝ     | Absolute difference of neighbouring pairs
     Œœ   | Split into odd and even indices
       §  | Sum of inner lists
        E | Equal

A monadic link taking a list of complex coordinates and returning 1 for tangential and 0 for not.
Based on @LuisMendo’s MATL answer so be sure to upvote that one!
Thanks to @JonathanAllan for saving a byte!

5ị€ can be ṁ5.

JavaScript (ES6), 74 bytes
Takes input as a list of coordinate pairs. Returns \$0\$ (falsy) for tangential or a non-zero value (truthy) for non-tangential.
a=>(g=_=>Math.hypot(([x,y]=a[i],[X,Y]=a[++i&3],x-X),y-Y))(i=0)-g()+g()-g()

Try it online!

I added a test case where all four sides have different lengths, and your code seems to fail on it.

@Bubbler Now fixed. My optimization was silly.

APL (Dyalog Unicode), 17 11 bytesSBCS
-6 bytes thanks to Bubbler
outputs 1 if tangential, 0 if not
0=-/|2-/5⍴⎕

Try it online!
Explanation:
0=-/|2-/5⍴⎕

          ⎕ take 4 complex numbers as evaluated input
        5⍴   reshape to 5
     2-/     difference between each pair of numbers
    |        absolute value
  -/         alternating sum
0=           the quadrilateral is tangential if the final result is 0

Previous answer
=/+/⍉2 2⍴|2-/5⍴⎕

Try it online!
Explanation:
=/+/⍉2 2⍴|2-/5⍴⎕

                ⎕  take 4 complex numbers as evaluated input
              5⍴    reshape to 5
           2-/      find the difference between each pair of numbers
          |         absolute value
      2 2⍴          reshape to 2x2 matrix
    ⍉              transpose
  +/                sum the rows
=/                  are they both equal?

11 bytes using alternating sum -/.

Thanks, @Bubbler I didn't knkow about that

05AB1E, 9 bytes
ĆüαnOtιOË

Try it online!
Port of Nick Kennedy's Jelly answer. It turned out pretty short, despite 05AB1E's lack of complex numbers.

Wolfram Language (Mathematica), 24 bytes
Returns Sphere if the quadrilateral is tangential, Insphere if it is not.
Head@Insphere@Polygon@#&

Try it online!

Wolfram Language (Mathematica), 38 bytes
Returns True if the quadrilateral is tangential, False if it is not.
0=={1,-1,1,-1}.Norm/@(#-RotateLeft@#)&

Try it online!

source: Stack Exchange

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

sort: votes


text:
Shortest Solution in Python 3 for Caught Speeding - CodingBat
I am trying to find the shortest code in python 3, to solve this problem:
You are driving a little too fast, and a police officer stops you.
Write code to take two integer inputs, first one corresponds to speed, seconds one is either 1 or 0, corresponding to True and False respectively to indicate whether it is birthday. Then compute the result, encoded as an int value:
0=no ticket,
1=small ticket,
2=big ticket.
If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases.
input:
60
0
Output:
0

input:
65
0
Output:
1

input:
65
1
output:
0

Here's my shortest solution (57 chars). Is there any way I can make it shorter in Python?
print(min(2,max(0,(int(input())-5*int(input())-41)//20)))

Reference: Problem inspired from this

@JoKing I did not know, I will add tips tag. Not sure if I want this to become a competition. If you recommend I can add code-golf as well.

What's the range of possible speeds? I think this can have a big effect on what shortcuts are possible.

It would be @xnor 0 to 199

Does it have to be in Python 3, or is Python 2 fine as well? I think Python 2 could save quite a number of bytes.

Python 3. Will add this in the question/tags.

@xnor but I will be interested if there's anything other than input that can save bytes in python 2.

Other than input and print without parens, Python 2 has cmp, which should let you do your method without the min/max clamping.

Python 3, 32 bytes
lambda a,b:(a-b*5>60)+(a-b*5>80)

Try it online!

Python 3, 50 49 bytes
If io must be done with stdin and stdout
a,b=map(int,open(0));print((a-b*5>60)+(a-b*5>80))

Try it online!
-1 byte thanks to @dingledooper

Ah! Beautiful! Thanks! Would accept in a while.

Save some characters by doing i=input; (-3) and then later i() (+8) for a total of +5 characters saved.

Do you mean like i=input;s=int(i())-5*int(i());print((s>60)+(s>80))?

@LMD could you show what you did? I tried this yesterday, couldn't shrink below 50 bytes.

@SayandipDutta, yeah, like Mukundan showed

@LMD The code I showed still uses 50 bytes

@Mukundan yeah, my fault

Late comment, but a,b=map(int,open(0)) would be just one byte shorter.

Python 3, 51 45 bytes
lambda a,b:min(2,max(0,(a//1-5*b//1-41)//20))

Try it online!
I was able to shave 6 bytes from your approach by using everyone's favourite python golfing keyword: lambda.
This turns your program into an anonymous function, which then can be called in the footer of a program.
Edit: I know that this question is way old, but I only just recently thought of using //1 to convert things to an integer instead of using int(...).

Thanks. But need to take input, and print as well. Meant to be a script, can't eval on repl :\

@SayandipDutta Functions are usually considered valid responses here

I'm sure they are. It's just that it didn't suit my usecase. I hope you understand :)

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


text:
Drum fill generator
Create a program that generates a drum fill. Your program will output a pattern of L (left hand hits), 'R' (right hand hits), and K for kick drum hits.
Rules

The pattern must never have more than 2 of the same hits consecutively.
The pattern must be loopable, so it mustn't have more than 2 of the same hits when it loops.
Your program accepts 1 argument which is the length of the pattern. You can assume this will always be an integer > 1.
Program output must be random each time it's ran.
It should be properly random each time, so that every combination is possible, so for an input of 2 for example: LR, LK, RL, RK, KL, KR all have a chance of being generated.
IO can be used with any convenient method.
Standard loopholes are forbidden.
This is code-golf, so smallest program wins!

Example valid output:
RLRRKKLL
LRLLKKLR
LKKRLRKLRRKL
LRLR

Example invalid output:
LRLL // 3 characters when looped
LRLRRRLLR // 3 characters in a row
RRLRLLRR // 4 characters when looped

No it should be properly random each time, so that every combination is possible, so for an input of 2: LL, LR, LK, RR, RL, RK, KK, KL, KR all have a chance of being generated. I'll add something to the rules about that now.

I've made those changes to the question, cheers!

May we output using three other distinct characters instead of L, R, K? (e.g. A, B, C or 2, 3, 9)

"The pattern must never have more than 2 of the same hits consecutively." What is this mean? Should I read for output hits[], forall i: hits[i] != hits[i+1]? But the example output RLRRKKLL doesn't agree on what I mean.

@tsh more than 2, not 2 or more.

@Adám So, does it mean $ \forall i: hits_i = hits_{i+1} \implies hits_i \ne hits_{i+2} $?

@tsh i'd make that $hits_{i+1\bmod n}$ and $hits_{i+2\bmod n}$, but yes.

05AB1E, 15 bytes
…LRKãʒDJÅγà3‹}Ω

Try it online!
…LRK                # literal "LRK"
    ã               # strings made of `input` of those letters
     ʒ       }      # filter:
      DJ            #  concatenate the string with itself
        Åγ          #  run-length encode
          à         #  maximum (largest run length)
           3‹       #  less than 3?
              Ω     # get a random element

Jelly, 15 bytes
“LRK”ṗ;`E3Ƥ$ÐṂX

A monadic Link accepting an integer which yields a list of characters.
Try it online!
How?
Pretty similar to Nick Kennedy's Jelly answer...
“LRK”ṗ;`E3Ƥ$ÐṂX - Link: integer, n
“LRK”           - "LRK"
     ṗ          - Cartesian power (all length n strings with alphabet "LRK")
            ÐṂ  - keep those entries which are minimal under:
           $    -   last two links as a monad:
      ;`        -     concatenate with itself
         3Ƥ     -     for each infix of length 3:
        E       -       all equal?
              X - random element

... but 1 byte shorter! Nice.

R, 67 bytes
n=scan();while(max(rle(c(x<-sample(c("L","R","K"),n,T),x))$l)>2)0;x

Try it online!
A full program taking an integer, n and implicitly printing the drum pattern.

I didn't notice the clever use of pasting the values together to duplicate the vector so  for a while thought it was possible to get something like LRLL.  Very nicely done.

Jelly, 16 bytes
“LRK”ṗ;`ŒɠṀ<ʋƇ3X

Try it online!
A monadic link taking the length \$n\$ and returning a Jelly string of the drum pattern. Like the other answers, assumes that \$n > 1\$
Explanation
“LRK”ṗ           | Cartesian power of "LRK" and n
            ʋƇ   | Keep those where the following is true:
      ;`         | - Concatenate to itself
        Œɠ       | - Lengths of runs
          Ṁ      | - Max
           <  3  | - Less than 3
               X | Pick one at random

Python 3, 115 \$\cdots\$ 112 104 bytes
from random import*
f=lambda n,s='L':any(b*3in s*3for b in'LRK')and f(n,''.join(choices('LRK',k=n)))or s

Try it online!
Saved a byte thanks to Chas Brown!!!
Saved 8 bytes thanks to Jonathan Allan!!!

112 bytes by using from random import* (a common trick).

Some improvements: 1. import*; 2. recursive lambda function; 3. multiply string (avoiding a space); 4. multiply by 3 (initial s='L' rather than s='LL'). 104 bytes

@ChasBrown Tried a few different imports but none of them saved any bytes -Thanks so much !! :-)

@JonathanAllan Totally amazing! Was trying to think of something recursive but didn't get anywhere. Also very clever changing over to s='L' and s*3! Thanks! :-)

APL (Dyalog Unicode), 30 bytesSBCS
Anonymous tacit prefix function.
{'LRK'[?⍺⍴3]}⍣{~1∊≢¨3∪/⍺,2↑⍺}⍨

Try it online!
{…}…⍨ apply the following function using the single argument also as left argument:
 'LRK'[…] index into the string "LRK" using the following indices:
  ⍺⍴3 reshape the number three into the length indicated by the left argument
  ? random indices in those ranges
⍣{…} keep applying that function until the following is true:
 2↑⍺ take the first two characters of the previously generated string
 ⍺, prepend the previously generated string
 3∪/ the unique elements in each window of width three (lit, the union-reduction)
 ≢¨ the length of each set
 1∊ is one a member thereof?
 ~ negate

R, 75 bytes
`?`=diff;n=scan();while(!all(??c(x<-sample(9+c(2,3,9),n,T),x)))0;LETTERS[x]

Try it online!
Rejection sampling until an allowable pattern is found. Samples \$x_i\$ from the set \$\{11, 12, 18\}\$ (the positions in the alphabet of K, L, R). Agreeably, these numbers are such that a pattern is allowable iff \$\forall i,  (x_{i+1}-x_i)-(x_i-x_{i-1})\neq 0\$. This condition is verified by calling diff twice (diff computes lagged differences, and here we want the lagged differences of the lagged differences).

How about this for 67 bytes?

@NickKennedy Smart! I always forget about rle. You should post this separately IMO.

ok thanks! Have done so it

Ruby, 57 bytes
->x{0while /(.)\1\1/=~(w=(%w(L K R)*x).sample(x)*'')+w;w}

Try it online!

You can save two sweet bytes by using ?redo:w instead of 0while +;w. See https://tio.run/##KypNqvyfZvtf1y6vWqPIVkO1vNpHIUjBu1YrT1OvODG3ICdVI09TS0lJU8vItk5fQ08zxjDGUN@@KDUl36qo9n@BQlq0cex/AA (I had come up with this answer before seeing yours, but it was too close and you got in first.)

JavaScript (ES6),  77  74 bytes
Assumes that the input is greater than \$1\$.
n=>(g=s=>s[n-1]?/(.)\1\1/.test(s+s)?g``:s:g(s+'LRK'[Math.random()*3|0]))``

Try it online!

Charcoal, 26 bytes
Ｎθ≔KηＷ⊙KLR№×η³×κ³≔⭆θ‽KLRηη

Try it online! Link is to verbose version of code. Hangs for an input of 1 (could be changed to output a random hit at a cost of 1 byte). Explanation:
Ｎθ

Input the number of hits.
≔Kη

Initialise the output to an illegal value.
Ｗ⊙KLR№×η³×κ³

Repeat while the output is illegal, determined by tripling the output and each of the three letters K, L and R, and checking whether one contains any of the others.
≔⭆θ‽KLRη

Assign the desired number of randomly selected letters to the output.
η

Output the final legal result.

Perl 5 -pa, 86 bytes
$_=R x("@F"+2);1while s|(.)(?=\1\1)|(R,L,K)[rand 3]|e;s/..$//;($_.$_)=~/(.)\1\1/&&redo

Try it online!

Ruby, 97 bytes
->x,y=->{[*1..x].map{%w[L R K].sample}}{a=y[];a=y[]while(a+a).chunk{|n|n}.any?{|_,e|e[2]};a.join}

Try it online!
This is a lambda function, which takes the length input as x.
It creates a function y which generates a list of length x containing random characters from the list ["L", "R", "K"]. It then checks to see if there are any repeating occurrences of more than 2, and if so recreates a random string.
The chunk method on an array groups consecutive elements.
I check for any repetitions on (a+a) (where a is the generated drum loop), to find any looping-round repetitions.
Golfy Tricks

Using e[2] instead of e.size > 2 - this works as everything is truthy in Ruby except nil and false, and indexing out of bounds in an array returns nil.
Using %w[L R K] instead of ["L","R","K"] or [?L,?R,?K] - This is ruby's whitespace-separated word array.

Red, 141 112 bytes
func[n][until[s: copy""loop n[append s random/only"LRK"]parse
rejoin[s s][any[copy t skip opt t ahead not t]]]s]

Try it online!

Perl 6, 55 bytes
{({S:g{.}=<R L K>.pick}...{!/(.)$0$0/}o*x 2).tail}o\*x*

Try it online!
Anonymous code block that takes an integer and returns a string of RKLs.
Explanation:
                                                  o\*x*  # Generate a string of n *s
{                                                }  # And pass to code block
 (                     ...                 ).tail   # Get the last element of the sequence
  {                   }      # Where each element is
   S:g{.}=       # Substitute each character of the previous string with
          <R K L>.pick   # A random character
                          {          }      # Until
                                      o*x 2 # The double of the string
                           !                # Does not
                            /(.)$0$0/       # Contain three of the same character in a row

Burlesque, 43 bytes
pe"LRK"jCB{J?+gw)-]>]3.<}f[sa0#Rx/x/jrn-]!!

Try it online!
Made trickier by the fact there is no "select random element from list" as far as I am aware. 15 bytes are just trying to select a random element.
pe      # Push inputs onto stack takes "SEED N"
"LRK"   # Literal LRK
jCB     # Form all combinations of length N
{
 J?+    # Double string
 gw     # Zip with length of consecutive vals
 )-]    # Take length
 >]     # Maximum
 3.<    # Less than 3
}f[     # Filter for
sa0     # Find number of matches
#Rx/x/j # Fiddle stack to get SEED 0 num_matches
rn      # Gen random ints
-]!!    # Select the first


text:
Make a random drum loop
Do randomly generated drum loops sound good?
A drum loop is a \$5\times 32\$ matrix \$A\$ of \$1\$s and \$0\$s such that

\$A_{1,1}=A_{1,17}=A_{2,9}=A_{2,25}=1\$,
for each \$i\$, the \$i\$th row has exactly \$f(i)\$ different \$1\$s, where \$ f(1)=3, f(2)=2, f(3)=6, f(4)=8, f(5)=5\$,
for each \$j\equiv 1\bmod 4\$, the \$j\$th column has exactly one \$1\$, and
for each \$j\not\equiv 1\bmod 4\$, the \$j\$th column has at most one \$1\$.

Here, the rows provide instructions for each of five drums, with each column representing a beat. In particular, the first row corresponds to a kick, while second row corresponds to a snare.
Write the shortest code that draws a matrix uniformly from the set of drum loops.
Feel free to use your code to draw a random drum loop, implement the drum loop on this website, and then post a link to your creation in your post. (Note that we only use the first 5 rows of this online beat maker.)
Edit 1: To be clear, we are using 1-based indexing: the row indices are \$\{1,\ldots,5\}\$ and the column indices are \$\{1,\ldots,32\}\$.
Edit 2: Judging by the current submissions, the answer to my original question appears to be "yes": randomly generated drum loops do sound good. Here are links to the current examples:

Random drum loop by @Arnauld
Random drum loop by @tom
Random drum loop by @KevinCruijssen

May we output the transposed matrix instead?

Just to clarify, I am  guessing that you want the code to generate a different drum pattern each time it is run with a different seed value rather than to produce a single 'random' pattern that is the same each time.

@Arnauld - Yes, you may output the transpose instead.

@tom - Correct. Each run of the code should produce an independent realization of the random matrix.

I assume $i,j$ are 1-based in your challenge description? It isn't mentioned anywhere whether the 5x32 matrix you describe uses 1- or 0-based indexing, so you might want to add that.

@KevinCruijssen - Good point. I clarified this in my post.

Can we output a matrix of True and False rather than 1 and 0?

@NickKennedy - yes.

Why can't I read "for each i, the ith row has exactly f(i) different 1s" -- what are "different 1s" meant? 1 is always an 1, there is only 1 1 and there can't be any different 1s. Where am I wrong?...

@AlexeyBurdin - There are exactly f(i) entries in the ith row that equal 1.

C (gcc), 413 394 389 379 378 360 342 327 307 299 298 293 bytes
#define F;for(b[8]=b[v=24]=3,n=0;n
#define B,b[n]==
a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(&i)F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);}

Try it online!
#define F;for(b[8]=b[v=24]=3,n=0;n
#define B,b[n]==
a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(time(0))F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);}

try it online -earlier algorithm 307 bytes
Many thanks to @ceilingcat for more byte savings (360 to 342 - then 342 to 328 and 327 to 307 - then modified algorithm from 328 to 299 and 298 to 293).
Compiles ok without #include<stdio.h> using the -w compiler flag, thanks to @Arnaud for pointing this out.
As written it generates a fresh sequence each time. If we are allowed manual intervention of a new number in srand to generate a different drum sequence with say srand(6); then we can save 16 bytes.
Thanks to @Arnaud who made asked the question about generating the transpose matrix, which is what this program does. Thanks also for suggesting the change from int to char for a[20] that saves 15 bytes. Also thanks for @Post Rock Garf Hunter who figured out a way to remove white space near the Bs and then saved more bytes fixing up the #defines so that F is included in R. `#define' tokens often seem to need whitespace so they are cleanly identified.
This code works on tio.run, but elsewhere may need to include time.h.
How the program works
logic:

setup
4 sounds are fixed (at 1,9,17,25)
remaining sounds to be distributed randomly are in a[20]
b[32] holds output - one cell for each beat (1 to 32, but in C of course 0 to 31)
4 of the b cells must have something (at 5,13,21,29)
remaining sounds randomly scattered to empty cells
r[24] holds list of empty cells (2,3,4, 6,7,8 etc. in C 0,1,2, 4,5,6 etc.)
execute
put in 4 fixed sounds
choose random sound from a to put in each of 4 cells with sounds
choose random cell from r to put in random sound from remaining a sounds (simplification to algorithm is possible here by putting remaining sounds one by one from 1 to 16 (or 0 to 15) in a random cell, but this gave more bytes..., but now thanks to @ceilingcat this is now smaller see tio.run link for details)
print result

this is a long version of the code without the #define and other space savers to show the logic, but with small differences e.g. in final version a is char * not int *
#include<stdio.h>
#include<stdlib.h>
int main()
{
  int a[20]={1,4,4,4,4,4,4,8,8,8,8,8,8,8,8,2,2,2,2,2},
    b[32]={},r[24],n,k,j,t=20,v=24;
  time_t q;srand(time(&q));
//random initialization

  for(n=0;n<24;n++n=0;n<v;n++)r[n]=n+n/3+1;
// set up r with list of cells that don't definitely have sound 012,456 etc.

  b[0]=b[16]=1;b[8]=b[24]=16;
//put in fixed sounds

  for (n=0;n<4;n++)
    {k=rand()%t--;b[4+n*8]=a[k];a[k]=a[t];}
//choose a random sound from a to put in each of 4 cells that must  have sound
// each sound selected is then replaced by the sound at the end of the list
// and the length of the list is reduced by one

  for (n=0;n<16;n++)
    {k=rand()%t--;j=rand()%v--;b[r[j]]=a[k];a[k]=a[t];r[j]=r[v];}
// random cell from remaining `r` cells and random sound are selected
// again after selection from list final item replaces selected and length
// reduced by one

  for (n=0;n<32;n++)
    {printf("%d%d%d%d%d\n",(b[n]==1),(b[n]==16),(b[n]==4),(b[n]==8),(b[n]==2));}
 // print out 0 and 1 from logical tests to print transpose matrix
  return 0;
}

Trivial golfing suggestion: remove all the unnecessary whitespace.

Suggested optimization for the initialization of a[].

@PostRockGarfHunter many thanks. I guess that after ) and " the compiler does not get confused by the lack of white space before the B.

Fiddling around with your defines a bit I could I removed another 10 bytes.

The general rule seems to be that gcc needs whitespace between macros and letters or numbers, but not other sorts of characters.  This is a pretty common rule for a lot of languages.

Probably the last thing I will see but since F is always followed by a space removing < from the end of its definition, and adding it instead of the space after each use, will actually save 1 byte.

You can omit #include<stdio.h>. You may compile with -w (using the Compiler flags section) to get rid of the warnings.

Here's a link to your creation: https://splice.com/sounds/beatmaker/b3054cbac7f1

Suggest &i instead of time(0)

@ceilingcat - how does that work?... well it does so great... - so I guess that the pointer for i is in effect a random number each time the code runs... !! Many thanks again.

Some platforms, like TIO, have Address Space Layout Randomization

JavaScript (ES6),  194 193  189 bytes
Returns \$M^T\$.
_=>(g=n=>n?g(/1/.test(c=m[R()*32|0])?n:n-=c[h()]=1):m)(16,a=[1,,6,8,5],R=Math.random,h=_=>a[y=R()*5|0]?a[y]--&&y:h(),m=[...Array(32)].map((_,x)=>(c=[0,0,0,0,0],x&3?0:c[x&7?h():x/8&1]=1,c)))

Try it online!
How?
Note: Columns and rows in the following explanation refer to the matrix described in the challenge. They are stored the other way around in this implementation.
Initialization
We define an array \$a\$ holding the number of hits that need to be added to each row, ignoring the 4 fixed positions.
a = [ 1, , 6, 8, 5 ]

We define the helper function \$h\$ that picks a random row among those that are not completely filled, and updates \$a\$ accordingly.
h = _ => a[y = R() * 5 | 0] ? a[y]-- && y : h()

We define a matrix \$m\$ of \$32\times5\$ filled with \$0\$'s, except the columns such that \$x\equiv 0\pmod 4\$ (using 0-indexing) which are initialized according to the rules described in the challenge.
m = [...Array(32)]          // set up 32 columns
  .map((_, x) => (          // for each column at position x:
    c = [0, 0, 0, 0, 0],    //   start with all values set to 0
    x & 3 ?                 //   if x mode 4 is not equal to 0:
      0                     //     do nothing
    :                       //   else:
      c[                    //     update c:
        x & 7 ?             //       if x mod 8 is not equal to 0:
          h()               //         use a random row
        :                   //       else:
        x / 8 & 1           //         fixed position: use either row 0 or 1,
                            //         depending on the parity of floor(x / 8)
      ] = 1,                //     set the hit
    c                       //   yield the final column
  ))                        // end of map()

Main loop
We randomly add the \$16\$ remaining hits on empty columns (which implies \$x\not\equiv 0\pmod 4\$) until all rows are filled.
( g = n =>                  // n = total number of hits to add
  n ?                       // if n is not equal to 0:
    g(                      //   do a recursive call:
      /1/.test(             //     test whether
        c = m[R() * 32 | 0] //     a randomly selected column c
      ) ?                   //     contains any '1'; if it does:
        n                   //       just pass n unchanged to try again
      :                     //     else:
        n -= c[h()] = 1     //       set the hit on this column, on a random row
                            //       and decrement n
    )                       //   end of recursive call
  :                         // else:
    m                       //   we're done: return m[]
)(16)                       // initial call to g with n = 16

thanks for the question about M transpose, that was really useful.

Here's a link to your creation: https://splice.com/sounds/beatmaker/ad842eea5cf7

Thanks for the explanation - I always learn so much from your submissions :)

05AB1E, 65 bytes
31Ý©8ˆ24ˆ40¯ǝ0ˆ16ˆ®¯KΩˆ48¯¦¦ǝ•Wk¤]•3ôεćи}˜.ržw8и«®¯K.r.¡4Ö}é˜ǝb€¦

Outputs as a transposed list of strings.
Try it online. (The footer pretty-prints this as the intended rows/columns. Feel free to remove the footer to see the actual result.)
Explanation:
31Ý                # Push a list in the range [0,31]
   ©               # Store it in variable `®` (without popping)
8ˆ                 # Add 8 to the global array
  24ˆ              # Add 24 to the global array as well
     40¯ǝ          # Replace the values at the indices of the global array with 40
0ˆ                 # Add 0 to the global array
  16ˆ              # Add 16 to the global array as well
     ®             # Push the [0,31] list from variable `®` again
      ¯K           # Remove all values of the global array (the [0,8,16,24])
        Ω          # Pop and push a random index from this list
         ˆ         # Add it to the global array as well
            ¯¦¦    # Push the global array with the first two (8,24) removed
          48   ǝ   # Replace the values at the remaining three indices with 48
•Wk¤]•             # Push compressed integer 533636834
      3ô           # Split it into parts of size 3: [533,636,834]
        ε          # Map over each integer
         ć         #  Extract head; pop and push remainder and head
          и        #  Repeat the remainder the head amount of times
                   #   i.e. 533 becomes [33,33,33,33,33]
        }˜         # After the map: flatten the list of list of integers
          .r       # And randomly shuffle it
            žw8и   # Then push a list of 8 32s
                «  # And merge it to the end of the list
®                  # Push the [0,31] list from variable `®` again
 ¯K                # Remove all indices stored in the global array
                   # (the [0,8,16,24] and one random index)
   .r              # Randomly shuffle these remaining indices
     .¡            # Group the remaining indices by:
       4Ö          #  Where this (0-based) index is divisible by 4
                   #  (which would be i % 4 == 1 for the corresponding 1-based index)
     }é            # After the group by, sort the two inner lists by length,
                   # so the indices divisible by 4 are before the other indices
       ˜           # And flatten it to a single list
ǝ                  # Then insert the shuffled integers at those shuffled indices
 b                 # Convert each integer to a binary string
                   # (32=100000;33=100001;34=100010;36=100100;40=101000;48=110000)
  €¦               # And then remove the leading "1" from each
                   # (after which the resulting list is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why •Wk¤]• is 533636834.

Here's a link to your creation: https://splice.com/sounds/beatmaker/96d2538ae65b

Jelly, 43 bytes
32s8Zs4ZḢ;FẊḣ⁴ƲƊḢŒœ;FẊ$ƲFṙ-“¥©€Þı‘œṖ;¹Ṭz0ZṖ

Try it online!
A niladic link that returns a 32x5 matrix of 1s and 0s representing the drum loop. The footer simply prints it concatenated and separated by newlines.
Explanation
32                                          | 32
  s8                                        | Split into groups of 8
    Z                                       | Transpose
     s4                                     | Split into groups of 4
       Z                                    | Transpose
               Ɗ                            | Following as a monad:
        Ḣ                                   | - Head
         ;    Ʋ                             | - Concatenate to following as a monad:
          F                                 |   - Flatten
           Ẋ                                |   - Shuffle list
            ḣ⁴                              |   - First 16
                       Ʋ                    | Following as a monad:
                Ḣ                           | - Head
                 Œœ                         | - Odd/even indexed items
                   ;  $                     | - Concatenate to:
                    F                       |   - Remainder of list flattened
                     Ẋ                      |   - Shuffled
                        F                   | Flatten
                         ṙ-                 | Rotate right 1 item
                           “¥©€Þı‘œṖ        | Split list before positions 4, 6, 12, 20, 25
                                    ;¹      | Concatenate to 32 (because 32 was the beginning of this niladic link)
                                      Ṭ     | Convert from lists of numeric indices to logical lists with 1s at those positions
                                       z0   | Transpose with 0 as filler
                                         Z  | Transpose
                                          Ṗ | Remove last (the sixth list introduced with the 32 above)

Python 3, 180 bytes
from random import*
r=range
s=sample
a=s(s([x for x in r(32)if x%4],16)+[x*8+4 for x in r(4)],20)
print([[i in t for i in r(32)]for t in[[0,16,a[0]],[8,24],a[1:7],a[7:15],a[15:]]])

Try it online!
Prints a logical matrix representing the drum loop.

Python 3, 400 \$\cdots\$ 361 338 bytes
from random import*
r=randrange
p=65537
def h(b=p):
 while b==p:b=p|1<<r(32)
 l=[b,16777472]
 for i in[6,8,5]:
  while bin(b).count('1')!=i:b=sum(1<<r(32)for j in[1]*i)
  l+=[b]
 return l
g=1
while g:
 l,g=h(),0
 for i in range(32):
  b=sum(j&1<<i!=0for j in l)
  if i%4:g|=b>1
  else:g|=b!=1
for i in l:print(f"{bin(i)[2:]:>032}"[::-1])

Try it online!
Full program outputs a \$5\times32\$ matrix of \$1\$s and \$0\$s.  Bit slow at times (\$\sim15\$ seconds), but you can't rush the creative process! :P

R, 138 bytes
s=sample
y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16)))
z=matrix(0,5,32)
z[1,c(1,17,y[1])]=z[2,c(9,25)]=z[3,y[2:7]]=z[4,y[8:15]]=z[5,y[16:20]]=1

Try it online!
A full program that implicitly prints the drum loop as a matrix of 1s and 0s.
Alternative using a third party package:
R + DescTools, 130 bytes
s=sample
y=s(c(8*0:3+5,s((1:32)[-(4*0:7+1)],16)))
sapply(list(c(1,17,y[1]),c(9,25),y[2:7],y[8:15],y[16:20]),DescTools::Unwhich,32)

RDRR it!
A full program that implicitly prints a logical matrix (in the transposed form).


text:
What's the Mayan date?
Just over seven years ago, everybody suddenly stopped talking about the Maya people. It is time to rectify that!
For clarification, I am talking about the Mesoamerican Long Count Calendar. Your program will have as input a date in the Gregorian Calendar, and as output the corresponding date from the aforementioned Mesoamerican calendar.
That calendar counts days since August 11, 3114 BCE. It divides that number of days into periods of different lengths. There's the single day, the Winal (20 days), the Tun (18 Winal, or 360 days), the K'atun (20 Tun, 7200 days), and the B'ak'tun (20 K'atun, 144 000 days).
So you have your number of days since the epoch, then you find out how many of each period fit in there. Let's take William the Conqueror's coronation date of December 25, 1066. We're not bothering with the Julian Calendar here - we're using the Proleptic Gregorian Calendar for dates in the distant past (including the Maya epoch): basically the system of leap days every four years, except years divisible by 100 but not by 400, which I trust you're all familiar with.
Between Christmas Day in 1066 and the Maya epoch date of August 11, 3114 BCE, there's 1526484 days. In that number, you can fit 10 periods of 144000 days, so that's our B'ak'tun. The remainder, 86484, can fit 12 periods of 7200 days, so that's the K'atun. The remainder is 84. That's less than 360, so our Tun is 0. You can fit 4 Winal though, leaving a remainder of 4 days.
Now concatenate all those numbers with full stops in between, in decreasing order of period length. The date of 25 December 1066 becomes 10.12.0.4.4.
(luckily, Wolfram|Alpha can verify it too)
Specification
Your program will take as input a date in the Gregorian Calendar, between January 1, 1 AD (7.17.18.13.3), and 31 December, 3999 AD (18.0.15.17.6). The date can be in any format you want (my test cases will be using ISO 8601) as long as it is in the Gregorian calendar.
That means, valid input formats include (but are not limited to) "22 MAR 2233", "7/13/2305", "20200107T000000Z", and "2020-01-07T00:00:00+00:00", even an array like "[7], [1], [2020]", depending on what your language parses the most easily or what approach you want to use. It is not allowed however to include any information beyond year, month, day of the month, time (has to be 00:00:00) and time zone (has to be GMT). Once I start allowing the day of the year, the Unix timestamp, a full-fledged DateTime data object (which contains a host of other values) or some other date tracking scheme, this issue would no longer be about converting a Gregorian date into a Mayan date, but only about representing a Mayan date. So basically, just stick with a primitive or a list of primitives for input.
It will output a string containing the corresponding Mayan date, as discussed above. It has to be a single string of numbers separated by periods; an int array is not allowed. Using a built-in Maya converter in your language (though I would be surprised if it had one) is not permitted either.
The question is tagged code-golf, so the shortest program in byte count wins!
Test cases
Gregorian; Mayan
1-1-1; 7.17.18.13.3
1-1-2; 7.17.18.13.4
1066-12-25; 10.12.0.4.4
2000-2-29; 12.19.7.0.1
2012-12-21; 13.0.0.0.0
2020-1-5; 13.0.7.2.11
2100-3-1; 13.4.8.8.6
2154-4-11; 13.7.3.6.10
3999-12-31; 18.0.15.17.6

Some languages provide a Date or DateTime type which support both Unix-timestamp and getting year / month / day. Will it be valid input format? Or must I use a string or list of 3 integers?

@tsh More clarification added to the OP.

I make it 7 years past apocalypse.

2100-3-1 test case is incorrect. Output should be 13.4.8.8.6 according to Wolfram.

@Grimmy Yep, I was off by a hundred years there… Thanks!

xkcd was right!

There really shouldn't be any 0th stuff in there. We don't have 0 AD or the 0th month or the 0th day, but the challenge might be more fun this way (more suited to programming).

@John the Gregorian calendar doesn't, but the Mayan one certainly does. Remember how that date in 2012 was 13.0.0.0.0?

05AB1E, 54 52 bytes
365*Š3‹¹α4т‚DPª÷®β•ë˜¿•ºS₂+²£`•H`Ø•OŽQív₂y-‰R`})R'.ý

Try it online!
First step: compute the day number.
365                # literal 365
   *               # multiply
                   #  => 365*year is left on the stack for now
Š                  # get the other two inputs
                   #  => day is left on the stack
3‹                 # is month less than 3? (returns 0 or 1)
  ¹α               # absolute difference with year
    4              # literal 4
     т             # 100
      ‚            # pair the two: [4, 100]
       DP          # product of (a copy of) the pair: 400
         ª         # append it to to the pair: [4, 100, 400]
          ÷        # int divide the year by each of those numbers
           ®β      # convert from base -1: y/4 - y/100 + y/400
                   #  => number of leap days is left on the stack
•ë˜¿•              # compressed integer 15254545
     º             # mirrored: 1525454554545251
      S            # split to a list of digits
       ₂+          # add 26 to each: [27, 31, 28, 31, 30, ...]
         ²£        # month first values of that list
           `       # dump all on the stack
                   #  => days in previous months is left on the stack
•H`Ø•              # compressed integer 1136750
                   #  => gregorian-mayan offset is left on the stack
O                  # sum the stack, giving the # of days since 0.0.0.0.0

Second step: convert that number to the appropriate notation.
ŽQí                # compressed integer 6866
   v      }        # for each digit:
    ₂y-            #  26 - digit (20, 18, 20, 20)
       ‰R`         #  divmod, reverse, then dump
                   #  (pushes the mod then the div)
           )       # wrap the stack in an array
            R      # reverse
             '.ý   # join by "."

Well done! I'm mildly curious why you need to define 365, but not any of the other values involved :O

@KeizerHarm I do define all the values involved, but 05AB1E has compressed integer literals. However, integers larger than 356 need 3 bytes in their compressed form, so a plain 365 is just as short.

@KeizerHarm I see loads of integers: 365; 3; 4; т(100); ®(-1); •ΘÏF•(5254545); ₂(26); •H`ó•(1136777); ŽQí(6866); ₂(26). ;) See this 05AB1E tip of mine if you want to understand how the compressed integers work. And the 26 and 100 are single-byte builtins. Nice answer Grimmy. Out of curiosity, how is the Base -1 used here after you've integer-divided by [4,100,400]?

@KevinCruijssen [a,b,c] converted from base n is a * n² + b * n + c. For n = -1, that gives a - b + c. y/4 - y/100 + y/400 is the number of leap days.

I am, very impressed. You're probably going to be the accepted answer if only because of how much work is in this. I assume you've made the day-counting part before?

@KeizerHarm The part that counts days in previous months is based partly on this answer. The rest is all new.

Python 3, 149 \$\cdots\$ 145 140 bytes
from datetime import*
def f(d):
 n,s=(date(*d)-date(1,1,1)).days+1137143,""
 for i in[144000,7200,360,20,1]:s+=f".{n//i}";n%=i
 return s[1:]

Try it online!
Takes Gregorian date as [year, month, day] list and returns Mayan date as f"{B'ak'tun}.{K'atun}.{Tun}.{Winal}.{Day}"(loosely as a python f-string).

This has an int array as output. I did specifically say that the output had to be a string of the ints concatenated with periods.

@KeizerHarm Ah, sorry missed that. Will fix.

I'll have to look up what an f-string is, but this works for me :)

@KeizerHarm f-strings combine "string".format() with in-string evaluation of expressions. And it turns out they're are useful for golfing too - just saved 3 bytes with them! :-)

fstrings aren't a return type, it's just a way of representing strings with extra methods of formatting, like how "abc" isn't any different from 'abc'

@JoKing What I mean is f"{1+1}"=="2".

I forgot to include the ping for @KeizerHarm's comment, sorry

@JoKing Got it, thanks!

JavaScript (ES6), 96 bytes
Assumes that the system is set up to UTC time (as the TIO servers are)
Takes input as 3 distinct parameters (year, month, day).
(y,m,d)=>[144e3,7200,360,20,1].map(k=>n/(n%=k,k)|0,n=new Date(y+4e3,m-1,d+395335)/864e5).join`.`

Try it online!
How?
We can't safely pass a year \$y<100\$ to the Date constructor, as it gets interpreted as \$1900+y\$. To work around this issue, we add \$4000\$ to the year. We make sure to use a multiple of \$400\$ so that we have the same properties regarding leap years.
The remaining number of days to reach Epoch from August 11, 3114 BCE + 4000 years is \$395335\$.

JavaScript (Node.js), 74 bytes
d=>(i=5,g=(a,m=20-8%--i)=>i?g(a/m|0)+'.'+a%m:a)(new Date(d)/864e5+1856305)

Try it online!
Input as yyyy-MM-dd format string.
Thanks Arnauld, save 4 bytes.

C# (Visual C# Interactive Compiler), 186 163 bytes
string f(int[]t){int x,n=(int)(new DateTime(t[0],t[1],t[2])-new DateTime(1,1,1)).TotalDays+1137143;return string.Join(".",new[]{144000,7200,360,20,1}.Select(e=>{x=n/e;n%=e;return x;}));}

Try it online!
Edit: Use int[] as input instead of DateTime to meet the specification better. Thanks @keizerharm for the hint

You're using a DateTime object as input. I think I was possibly being too vague with the specification, but this goes against the idea of "the input may only contain day, month, year information". A DateTime contains a lot more than that. It, for example, allows direct subtraction of one such object from another.

Make the input three ints and move the initialisation of the DateTime to be inside the method based on that input, and it'll be alright.

Yep, that works!

168 bytes

C (GCC) 239 200
-39 bytes ceilingcat
#define S d/m;d%=m;m
l(y){y=y%(y%25?4:16)<1;}b,k,t;D(y,m,d){for(d+=1137110+L" ?[z˜·ÕôēıŐŮ"[m-1]+(m>2?l(y):0);--y;d+=365+l(y));m=144e3;b=S=7200;k=S=360;t=S=20;y=S=1;printf("%d.%d.%d.%d.%d",b,k,t,y,d);}

Try it online!

@ceilingcat Nice trick with the string literal for the array. What does the z prefix specify? I can't find it in any documentation?

If you mean L"..." prefix, it denotes a string of wide chars that happen to be the same length as ints on TIO.

Ah, I got confused looking at it and thought the z~ was a z" and I didn't notice the L" earlier


text:
Random spanning tree of a rectangular grid
Significantly harder version of Spanning tree of a rectangular grid.
Background
A spanning tree (Wikipedia) of an undirected graph is a subgraph that is a tree which includes all of the vertices of the original graph. The following is an example of a spanning tree of a 4-by-4 grid graph.

Task
Given two positive integers w and h, output a randomly generated spanning tree of the grid graph which has w vertices horizontally and h vertices vertically. Your program/function should be able to generate every possible spanning tree with nonzero probability.
One possible algorithm to solve this task is random minimum spanning tree, which calculates the minimum spanning tree of the given graph with randomized edge weights.
Input and output
The input is two positive integers w and h.
The output is a representation of a spanning tree. You can choose any representation that can describe such a graph without ambiguity, which includes (but is not limited to):

ASCII-formatted grid
A standard graph structure, e.g. adjacency matrix, adjacency list, incidence matrix...
A list of pairs of numbered vertices

Please specify the output format in your submission.
Scoring & winning criterion
The standard code-golf rules apply. The shortest valid submission in bytes wins.
Example I/O
w=3, h=2

ASCII grid

+-+-+
| |
+ +-+

Adjacency matrix

0 1 0 1 0 0
1 0 1 0 1 0
0 1 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 1
0 0 0 0 1 0

List-of-vertex-pairs representation

[(0, 1), (0, 3), (1, 2), (1, 4), (4, 5)]

or
[((0, 0), (0, 1)),
 ((0, 0), (1, 0)),
 ((0, 1), (0, 2)),
 ((0, 1), (1, 1)),
 ((1, 1), (1, 2))]

w=1, h=1
The graph is a single vertex with no edges, and its only spanning tree is the graph itself.

See my answer; are complex number coordinates to distinguish vertices allowed?

@ValueInk Yes, it's allowed.

As the challenge stands now, I could generate graphs randomly, check if the current graph is a spanning tree, else repeat. The program will have random running time (usually very large), but will finish with probability 1. You may want to rule that out (not sure how). Or is that acceptable?

@LuisMendo I was about to go write an algorithm doing exactly like that to make a point... BogoSpanningTree

The randomness part of the challenge seems needlessly tacked on to a perfectly fine challenge.

Is it acceptable for my ASCII grid to bordered by whitespace on all sides?

@Neil Yes, it's fine.

@LuisMendo I have no problem with such a solution (though the challenge was indeed inspired from the "minimum random spanning tree" Wikipedia article).

Python 2, 134 bytes
from random import*
w,h=input();w+=1
t={1}
while 1:z=choice([{a,b}for a in t for b in{a-1,a+1,a-w,a+w}-t if b%w>0<b<w*h]);print z;t|=z

Try it online!
A small improvement over xnor's answer by using row size w+1 instead of w and not using the zeroth column. For example, the following coordinates are used for the input 3,2:
1-2-3
| | |
5-6-7

Bountied! I'll keep it up for the 7 days to give you more views.

Wolfram Language (Mathematica), 146 bytes
Block[{c,g=GridGraph@{##}},Graph[Range[1##],Join@@Reap[Do[c@n/._c:>#0[Sow[#<->n];n],{n,RandomSample@AdjacencyList[g,c@#=#]}]&@1][[2]],Options@g]]&

Try it online!
Based on my answer to the question Maze Generation.
Returns a Graph object.
For example, w = 20, h = 20 gives:

Ruby, 159 bytes
->w,h{c=(v=[*1..w].product [*1..h]).product;((f,(a,b)),(g,(d,e))=c.shuffle.map{|z|[z,z.sample]};(c=c-[f,g]+[f+g];p(a,b,d,e))if(a-d).abs+(b-e).abs<2)while c[1]}

Try it online!
Uses simple Kruskal's algorithm with a few pessimizations (no union-find, inefficient - and non-uniform! - sampling of the purely virtual edge list, returns via stdout), at a byte cost relatively close to Value Ink's Prim implementation.
Prints each edge as a set of four lines; if you want something slightly more sensible, replace p(a,b,d,e) with p [a,b,d,e] at the cost of one byte.
Unsqueezed version:
->w, h{
 v=[*1..w].product [*1..h]
 c=v.product
 while c.size > 1
  (f, (a, b)), (g, (d, e)) = c.shuffle.map{|z| [z, z.sample]}
  if (a-d).abs + (b-e).abs < 2
   c = c - [f, g] + [f + g]
   p [a,b,d,e]
  end
 end
}

The algorithm I used has a name?? Also you should add a TIO link

+1 for the word "pessimization".

@ValueInk there are two different ways [Prim's algorithm}(https://en.wikipedia.org/wiki/Prim%27s_algorithm) can be turned into a maze generator algorithm. If you randomize edges once at the beginning, it returns the same distribution as Kruskal's algorithm. If you pick a random edge at each step, you get a markedly different type of maze, that prefers paths towards the origin

Jelly, 28 bytes
,þ;Z$ṡ€2ẎẊḣ1;ẎḟL’ɗÐḟ@ḣ1ʋ¥ƬƊṪ

Try it online!
A dyadic link taking the width and height as its arguments and returning a list of pairs of vertices indicating the edges of the random minimum spanning tree. Based on Prim’s algorithm with the edge costs randomised.
Explanation
,þ                           | Outer table using pair function
    $                        | Following as a monad:
  ;                          | - Concatenate to:
   Z                         | - Transposed table
     ṡ€2                     | Split each into overlapping lists of length 2
        Ẏ                    | Join outer lists
         Ẋ                   | Randomise order
                          Ɗ  | Following as a monad:
          ḣ1                 | - First list item (still in a list)
                        ¥Ƭ   | - Repeat following as a dyad, collecting up results, until no new result seen (will have the randomised list of vertex pairs as its right argument)
            ;          ʋ     | - Concatenate to the following as a dyad:
             Ẏ               |   - Join outer lists (making list of vertices seen so far)
                 ɗÐḟ@        |   - Keep only items from the randomised list of edges where the following is false:
              ḟ              |     - Filter out the vertices already used
               L             |     - Length
                ’            |     - Decrement by 1
                     ḣ1      |   - First list item (still in a list)
                           Ṫ | Final iteration of the above

Ruby, 185 164 bytes
A huge mess. Outputs a vertex-pair list, where vertex coordinates are complex numbers in the form x+yi.
Long story short, it takes all vertices that have already been chosen, randomly picks a neighbor that has not been picked before, and attaches it to the graph, then repeats the process until all vertices have been chosen.

-4 bytes by optimizing r>=0&&i>=0 to r|i>=0 -- If either number is negative, the bit-or will ensure that the combined result is negative.
-17 bytes by realizing my filter function in the second neighbor check could be switched to a simple set intersection...

->w,h,*e{*v=q=0i;d=1,-1,1i,-1i
(q=v.flat_map{|x|d.map{|c|x+c}.select{|e|r,i=e.rect;r|i>=0&&r<w&&i<h}-v}.sample
(v<<q;e<<[(d.map{|c|q+c}&v).sample,q])if q)while q;e}

Try it online!
Explanation
->w,h,*e{                                       # Proc taking 2 arguments, e=[]
         *v=q=0i;                               # Add first vertex 0+0i to list
                 d=1,-1,1i,-1i                  # Save 4 cardinal directions
(                                     )while q  # While there is a valid neighbor:
 q=                                             # Set next vertex to:
   v.flat_map{|x|d.map{|c|x+c}                  # Get all neighbors to used vertices
      .select{|e|                               # Filter neighbors by:
                 r,i=e.rect                     # Get real/imaginary components
                 r|i>=0&&r<w&&i<h               # Vertex coordinates are in-bounds
             }
      -v                                        # Filter already-used vertices
    }.sample                                    # Pick a random valid neighbor
 (                                   )if q      # If a neighbor was found:
  v<<q                                          # Add it to the vertex list
  e<<[                                          # Add an edge to the edge list.
      (                                         # First vertex of edge is:
       d.map{|c|q+c}                            # Get vertex neighbors
       &v                                       # Intersect w/ used vertices
      ).sample                                  # Pick one by random
      ,q]                                       # Second vertex of edge is neighbor
                                                # (end while)
e                                               # Return the edge list

K (ngn/k), 64 bytes
{e@&~~':i{@[x;&|/x=/:y;:;&/x y]}\e:0N?,/(2':'m),+'2':m:x#i:!*/x}

Try it online!
arg: w,h pair. result: list of vertex pairs.
i:!*/x create the list 0 .. (w*h)-1 and assign to i
m:x# reshape to a w-by-h matrix m
2': pairs of neighbouring rows
+' transpose each (make them rows of pairs)
( ), prepend
2':'m pairs of neighbouring cells in each row
,/ concat into a single list
e:0N? shuffle and assign to e for "edges"
i{ }\ scan the edges with the function in { } and a starting value i.
the left arg will map vertices to their "tree ids" in the forest.
initially the vertex ids and tree ids coincide.
@[x;&|/x=/:y;:;&/x y] amend the current forest by merging the tree(s) corresponding to the ends of the new edge
~': which forests match the previous ones? boolean list
e@&~ select from e where not

Python 2, 136 bytes
from random import*
w,h=input()
t={0}
while 1:z=choice([{a,b}for a in t for b in{a-~a%w/~w,a+a%w/~w,a-w,a+w}-t if-1<b<w*h]);print z;t|=z

Try it online!
Prints edges as two-element set of vertices given by single-number index, terminating with error. The strategy is to to build up the set of vertices t in the tree until it contains the whole rectangle rectangle. At each step, we add an edge to the spanning tree consisting of a vertex in t and one of its neighbors that's not in t, and we add the new vertex to t. We search for neighbors by adding one of {1,-1,w,-w} to the 1D index with some trickery to avoid unwanted wraparounds, and checking that the result lies within the bounds of the rectangle.

Python 2, 142 bytes
from random import*
w,h=input()
t={0}
while 1:z=choice([{a,b}for a in{k/w+k%w*1jfor k in range(w*h)}-t for b in t if(a-b)**4==1]);print z;t|=z

Try it online!
Prints edges as two-element sets of complex numbers, terminating with error.

-2 bytes to your top solution.

Which means that Bubbler is eligible for a bounty.

JavaScript (ES6),  151 147 145  143 bytes
Takes input as (width)(height). Returns a list of pairs of numbered vertices.
w=>g=h=>(m=1,n=a=[],F=v=>[++v%w&&v,--v%w&&v-1,v+w,v-w].map(V=>V<0|V/w/h|m>>V&1|Math.random()<.5||F(V,m|=1<<V,n=a.push([v,V]))))``|~n+w*h?g(h):a

Try it online!
Commented
w =>                        // w = width
g = h => (                  // h = height
  m = 1,                    // m = bitmask of visited vertices
  n =                       // n = number of visited vertices - 1
  a = [],                   // a[] = pairs of connected vertices
  F = v =>                  // F is a recursive function, taking the current vertex v
    [ ++v % w && v,         //   try v + 1 if (v + 1) mod w is not equal to 0
                            //   we temporarily increment v to coerce it to a number
      --v % w && v - 1,     //   decrement v; try v - 1 if v mod w is not equal to 0
      v + w,                //   unconditionally try v + w
      v - w                 //   unconditionally try v - w
    ].map(V =>              //   for each new vertex V:
      V < 0 |               //     abort if V is negative
      V / w / h |           //     abort if V is greater than or equal to w * h
      m >> V & 1 |          //     abort if V was already visited
      Math.random() < .5 || //     abort with 50% probability
      F(                    //     otherwise, do a recursive call:
        V,                  //       using the new vertex
        m |= 1 << V,        //       update the bitmask of visited vertices
        n = a.push([v, V])  //       append [v, V] to a[] and update n
      )                     //     end of recursive call
    )                       //   end of map()
)`` |                       // initial call to F with v = [''] (zero'ish)
~n + w * h ?                // if n is not equal to w * h - 1:
  g(h)                      //   try again
:                           // else:
  a                         //   success: return a[]

Charcoal, 77 63 bytes
ＮθＮηＪ⊗‽θ⊗‽ηＰ+  ¦+Ｗ‹№ＫＡ+×θη«Ｊ⊗‽θ⊗‽η¿¬℅ＫＫ«≔⌕ＡＫＶ ι¿ι«Ｐ+  Ｐ✳⁻χ⊗‽ι²+

Try it online! Link is to verbose version of code. Outputs a whitespace-bordered ASCII grid. Explanation:
ＮθＮη

Input the width and height.
Ｊ⊗‽θ⊗‽ηＰ+  ¦+

Jump to a random position and mark it with a + surrounded with spaces. (Unfortunately Charcoal's Multiprint operator special-cases a leading + so I have to output the + separately.)
Ｗ‹№ＫＡ+×θη«

Repeat until w*h +s have been output.
Ｊ⊗‽θ⊗‽η

Jump to a random position.
¿¬℅ＫＫ«

If the position is vacant,
≔⌕ＡＫＶ ι

find any neighbouring spaces,
¿ι«

and if there is at least one, then
Ｐ+  Ｐ✳⁻χ⊗‽ι²+

surround the current position with spaces, draw a - or | in a random matching direction, and finally draw a + in the current position.

R, 156 bytes
function(w,h){b=rbind(x<-1:(s=w*h),c(x+1,1:(s-h)+h))[,1:w*-h][,sample(s+s-h-w)]
y=b[,1]
while(!all(z<-matrix(b%in%y,2)))y=rbind(y,b[,colSums(z)==1][1:2])
y}

Try it online!
A function taking the width and height and returning a two-matrix of 1-indexed pairs of points (numbered from top left, moving down and then right). The footer also prints an ASCII representation. Implements Prim’s algorithm.


text:
Shorten String as Much as Possible
Introduction
In a list of strings, there is a certain length you can shorten strings to before they become indistinguishable. This is a pretty bad explanation, so here is an example.

['hello', 'help', 'helmet']
['hell', 'help', 'helme']
['hell', 'help', 'helm']
['hel', 'hel', 'hel'] <- At this point the strings are indistinguishable

Challenge
Given a list of strings, you program must shorten them until just before any of them become indistinguishable. Shorting is defined as removing one character from the end of a string. To shorten a list of strings by one remove the last character from all of the longest strings in the list, or, if all strings are the same length, every string in the list. For example, given the above input, your program would output ['hell', 'help', 'helm']. If the strings cannot be shortened, or are already indistinguishable, your program should just output the list unchanged. If, at any point, shortening the strings in the list would make some, but not all, of the strings indistinguishable, you program should still output the list as is, instead of shortening it more.
Note for those who are wondering: If multiple strings can be shortened in the list, they should all be shortened.

Your program may take input in any format you like, as long as it is one of the default I/O methods. Input can be of any encoding, but must be a valid UTF-8 string, or your language's equivalent, as can the list of strings. The strings will never be empty, but they might be of different lengths. They will always have at least one common character or be all the same length. There are no restrictions on string content, other than this. The list can also be of any length.
The same goes for output: you may use any of the default I/O methods. Output can be of any encoding and type, just like the input. All strings in the output should be the same length.

Example I/O

['hello', 'help', 'helmet']
['hell', 'help', 'helm']
['like', 'likable', 'lick']
['like', 'lika', 'lick']
['hello', 'hello', 'hello']
['hello', 'hello', 'hello']
['a1', 'a2', 'bb']
['a1', 'a2', 'bb']
['farm', 'farms', 'farmer']
['farm', 'farms', 'farmer']
['ape', 'bison', 'caterpillar']
['a', 'b', 'c']
['', '', '']
['', '', '']

Scoring
This is code-golf, so the shortest answer in bytes wins!

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

Charcoal, 54 bytes
≔⌊ＥθＬιζ≔⌈ＥθＬιδ≔ＥδＥθ…λ⎇‹ιζι⌈⟦ζ⁻⁺ιＬλδ⟧η≔Φη⬤ι⁼№ιλ¹η⎇η§η⁰θ

Try it online! Link is to verbose version of code. Explanation:
≔⌊ＥθＬιζ≔⌈ＥθＬιδ≔Ｅδ

Get the length of the shortest and longest strings, and loop over the latter.
Ｅθ…λ⎇‹ιζι⌈⟦ζ⁻⁺ιＬλδ⟧η

Trim each string appropriately; the longest string simply trims a character each time but shorter strings stop when they reach the length of the shortest string, until finally the longest string joins them and all the strings can be trimmed again.
≔Φη⬤ι⁼№ιλ¹η

Filter out the results with indistinguishable prefixes.
⎇η§η⁰θ

Print the shortest distinguishable prefixes, or failing that, the original strings.

@JonathanAllan Thanks, I think I have that behaviour now.

Jelly, (11?) 18 bytes
This follows the example given in the question rather than "To shorten a list of strings by one remove the last character from all of the longest strings in the list, or, if all strings are the same length, every string in the list."
Ṗ€µẈnṂ$TȯJµ¦ƬQƑƇṪȯ

Try it online! Or see the test-suite.
(Both use the footer to format the resulting list of strings).
How?
Ṗ€µẈnṂ$TȯJµ¦ƬQƑƇṪȯ - Link: list, S
            Ƭ      - collect up until a fixed point applying:
           ¦       -   sparse application...
  µ       µ        -   ...to indices: this monadic chain:
   Ẉ               -       length of each
      $            -       last two links as a monad:
     Ṃ             -         minimum
    n              -         not equal (vectorises)
       T           -       truthy indices
         J         -       range of length (of current list) - i.e. all indices
        ȯ          -       logical OR
Ṗ€                 -   ...action: pop each
               Ƈ   - filter keep those for which:
              Ƒ    -   is invariant under:
             Q     -     deduplicate
                Ṫ  - tail (0 if none remain)
                 ȯ - logical OR with S (for the 0 case)

If the text is correct rather than the example then this works for 11 bytes:
ḣ€ⱮẈṀ$QƑƇḢȯ

A monadic Link accepting a list which yields a list.
Try it online! Or see the test-suite.
(Both use the footer to format the resulting list of strings).
How?
ḣ€ⱮẈṀ$QƑƇḢȯ - Link: list, S
     $      - last two links as a monad - f(S):
   Ẉ        -   length of each
    Ṁ       -   maximum
  Ɱ         - map across (implicit range [1..m]) applying:
ḣ€          -   head each to index
        Ƈ   - filter keep those for which:
       Ƒ    -   is invariant under:
      Q     -     deduplicate
         Ḣ  - head (0 if none remain)
          ȯ - logical OR with S (for the 0 case)


text:
Caddyshack or: How to compress already-golfed code
In golf, a knowledgable caddie helps an already good golfer to be even better. In this challenge, you build a "caddie" to help you code golf. In particular, your caddie will compress golfed code in such a way that another program can uncompress and then run the code. A good caddie will compress golfed code to be much smaller than the original golfed code. In fact, in caddie-assisted Python (say), you might be able to golf on par with a Jelly golfer!
Formally, a caddie for a language L is a pair (E,D) of programs. The program E takes as input any code c in L and outputs a string s. The program D takes s as input along with any input x of c and returns the output of c(x). We do not require E and D to be written in L. You could say that E is a transpiler that converts c into a version s that runs in the language D. We are interested in transpilers E for which E(c) tends to be smaller than c, even when c is already golfed.
Write a caddie (E,D) for any language L of your choosing. When you first post a caddie here, its score is infinity. Use the following method to update your score:

Let C denote the challenge in code-golf with at least 10 points that was posted first after your submission.
Let c denote the shortest posted solution to C that is written in L.
Your score is infinity unless C and c both exist, at which point your score is size(E(c))/size(c).

Recompute your score whenever either C or c changes. Lowest score wins.

This is a very nice question imho.

I am a bit confused about "The program D takes s as input along with any input x of c and returns the output of c(x)." Does this just mean that D is the inverse of E? Or does D have to work for any caddy?

@sugarfi - D is designed with E, for E. One possibility is that D uncompresses s to obtain c and then evaluates c on input x. Yes, this conversion from s to c can be thought of as the inverse of E.

Is Japt a valid caddie for JavaScript?

@a'_' - If there's a program E that converts from JavaScript to Japt, then it's valid, yes.

I have a question about the string s - can it be effectively binary - a set of bytes with values of 0-255 - or should it be restricted to 'bytes that can be printed'. Is it envisioned that s can be printed as 'code' in a Code-Golf post? Do you have a list of characters we should not use? Oh and great challenge.

@tom - I'm not so picky about s. A set of bytes with values of 0-255 will suffice for this challenge.

Python 3 Caddy, interprets BrainF***
Score: \$\frac{38}{224}\approx0.17\$ (with newlines removed)
Program E
from textwrap import wrap

x = input('Code: ')
i = ['<', '>', '+', '-', '[', ']', '.', ',']
o = ''
for c in x:
    if c in i:
        o += str(i.index(c) + 1)
if o:
    d = wrap(o, 6)
    d = [int(x) for x in d]
    o = ''
    for c in d:
        o += chr(int(c) + 128)
print('Compressed: ', o)

The way this works is by converting every instruction in the input to a digit, then concatenating those digits to a number. Then it splits that number into 6-digit groups and converts each to a Unicode character. (A number higher than 6 could be used, by that would cause errors for large programs). Then it outputs it.
Program D
x = input('Compressed: ')
p = input('Input: ')
p = list(p)
d = ''
for c in x:
    c = ord(c) - 128
    d += str(c)
d = d.replace('-', '')
i = ['<', '>', '+', '-', '[', ']', '.', ',']
o = ''
for n in d:
    n = int(n) - 1
    o += i[n]
tape = [0] * 30000
head = 0
m = {}
m2 = {}
stack = []
for i in range(len(o)):
    char = o[i]
    if char == '[':
        stack.append(i)
    elif char == ']':
        begin = stack.pop()
        m[begin] = i + 1
        m2[i] = begin
i = 0
while i < len(o):
    char = o[i]
    if char == '<':
        head -= 1
        i += 1
    elif char == '>':
        head += 1
        i += 1
    elif char == '+':
        tape[head] += 1
        i += 1
    elif char == '-':
        tape[head] -= 1
        i += 1
    elif char == '[':
        if tape[head] == 0:
            i = m[i]
        else:
            i += 1
    elif char == ']':
        if tape[head] != 0:
            i = m2[i]
        else:
            i += 1
    elif char == '.':
        print(chr(tape[head]), end='')
        i += 1
    elif char == ',':
        try:
            tape[head] = ord(p.pop(0))
        except:
            tape[head] = 0
        i += 1

This is pretty simple, it just reverses the compression algorithm and evaluates the result.

FYI - Here is a link to what is currently challenge C for your post, but I don't see a solution coded in BrainF*** yet: https://codegolf.stackexchange.com/questions/197879/convert-a-32-bit-binary-ipv4-address-to-its-quad-dotted-notation

@DustinG.Mixon - yeah, I checked the new challenges, but none had a solution in BrainF***

Also, you are allowed to post a BrainF*** solution to that challenge and then compress it here.

@DustinG.Mixon - ok, I will do that soon

@DustinG.Mixon - Finally found a BrainF answer! Updating my score now.

I don't see a BrainF answer for that challenge. Am I missing something?

@DustinG.Mixon - Which challenge? I got this one from "Add two numbers".  I would have posted one on a new challenge, but I am not any good at BrainF.


text:
Integer Keys and Duplicates
Given a non-empty list/vector of positive integers, write a function to check the following conditions in as few bytes as possible.

Take the first integer (the key, or k1) and check that the next k1 values have no duplicate values, excluding instances of k1.
Take the last integer (the second key, or k2) and check that the k2 values before k2 have no duplicate values, excluding instances of k2.

Note that both keys, k1 and k2, are elements of the list/vector as either key could contain the other.
Also, k1 and/or k2 can be greater than the number of integers within the list, which means you should check every element of the list except for instances of the given key for duplicates.
If both steps return True, return True, else, return False.
NOTE: It should be rather intuitive that searching for duplicates within the first k1+1 elements excluding instances of k1 will exclude the first element, or k1. Some answers I've seen "pop" k1 off the list and do the test on the next k1 elements. Either method yields the same results. This is also true for k2 and it's test.
Test Cases
[5,1,2,5,3,4,3] is TRUE because [k1=5][1,2,5,3,4] has no duplicates, nor does [5,3,4][k2=3] have any duplicates, excluding instances of k3.

[6,9,12,15,18,19,8,8,3] is FALSE because [k1=6][9,12,15,18,19,8] has no duplicates while [19,8,8][k2=3] has a duplicate.

[100,100,100,100,101,102,3] is TRUE because [k1=100][100,100,100,101,102,3] has no duplicates, and [100,101,102][k2=3] has no duplicates.

[100,100,100,100,101,102,4] is FALSE. [k1=100][100,100,100,101,102,4] has no duplicates, but [100,100,101,102][k2=4] has duplicates.

[6,6,6,6,6,6,6,3,3,3,3] is TRUE. [k1=6][6,6,6,6,6,6] has no duplicates, excluding instances of k1, and [3,3,3][k2=3] has no duplicates, excluding instances of k2.

[1,2] is TRUE (clearly)

[1] is TRUE (clearly)

I would argue that the empty list falls under "undefined behavior" since there is no "first" or "last" element to look at!

Can you expand upon why [3, 3, 3] "has no duplicates"? It naively seems to me that there are at least 2 3s, so I would say that's a duplicate.

@ChasBrown I think this part should be made a bit more explicit, but the important point here is that the value of the key ($3$ in this example) is always excluded from the test (see: excluding k1 and excluding k2).

Okay that's better!

@ValueInk and others, if I update the challenge so that the empty list is undefined, would that change anyone's answers? I could make it self-defined, where the users answer could be any type of answer, False, True, or undefined. Thoughts?

My original code that didn't account for empty lists used to throw an error on the empty list input, so my answer would save 2 more bytes if you implemented the rule change ;) But golfing reasons aside, I still believe an empty list has no "first" or "last" element, so you have no actual "keys" to work with.

@Sumner18 Generally, undefined behaviour means that you can assume that your program won't be given this as input, in the same way that you don't have to handle being given a string or a number instead of a list. Really, Exceptional Edge Cases are something it is recommended to avoid

Thanks @JoKing. I didn't know about the Exceptional Edge Cases. I will make the edit. If this helps anyone shave bytes off of their code, feel free to change.

JavaScript (ES6),  88 75 71  69 bytes
a=>(g=_=>!a.reverse().some(o=(v,i,[k])=>v-k&&o[v]&(o[v]=i<=k)))()&g()

Try it online!
Commented
The function \$g\$ reverses the input array and performs the test with the resulting leading key.
g= _ =>               // g takes no explicit input
  !a.reverse()        // reverse the input array a[]
  .some(o =           // we use the object o to store encountered values
    (v, i,            // for each value v at position i in a[],
           [k]) =>    // with k = leading value:
      v - k &&        //   abort if v is equal to the key
      o[v] &          //   otherwise, test whether o[v] is already set
      (o[v] = i <= k) //   and i is less than or equal to the key,
                      //   in which case o[v] is set
  )                   // end of some()

The main function simply invokes \$g\$ twice.
a => g() & g()

I thought I could read JavaScript okay. I thought wrong.

Syntactically, what is happening here: .some(o = ?  A callback function is expected -- why is it ok to use an assignment to a callback instead?

@Jonah In JavaScript, assignments are a type of expression, and such "assignment expressions" evaluate to the value being assigned. In this case, o=()=>{} is an expression evaluating to a function value, which is passed as an argument to .some().

Jelly, 12 bytes
,Uḣ⁹ḟQƑʋḢ$€Ạ

Try it online!
A monadic link taking a list of integers and returning a Jelly Boolean (1 for True, 0 for False).
Explanation
,U            | Pair with reversed list
       ʋḢ$€   | For each pair, do the following as a dyad using the popped head as the right argument y:
  ḣ⁹          | - First y integers
    ḟ         | - Filter out y
     QƑ       | - Check if invariant when uniquified
           Ạ  | All

Python 2, 95 88 75 74 bytes
lambda x:all(A[:A[0]+1].count(a)<2for A in[x,x[::-1]]for a in A if a-A[0])

Try it online!
7 bytes saved thx to Jo King; then 8 more thx to Value Ink; and then 5 more from Jo King; and 1 byte thx to mypetition pointing out an extra space.
Function taking a list of ints; returns False/True.

I'm pretty sure you can check in A instead of in A[:A[0]+1] to save 8 bytes. You're only counting entries within the slice anyways, so if the same value is outside the slice, it's not going to affect the count either way. (Same goes for the alternate answer, which saves 3 bytes.)

@ValueInk and Jo King: Thanks, gentle-persons!

Your code has a useless trailing space, so you actually have a score of 74.

Charcoal, 31 bytes
∨¬⮌θ⬤Ｅ⟦⮌θθ⟧✂⮌ι⁰⊟ι¹⬤ι∨⁼№ιλ¹⁼λ§ι⁰

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, which is - for true and nothing for false. Explanation:
∨¬⮌θ

If the reversed list is empty then the result is true. (Don't ask me why I need to reverse the list first... I think the implicit input uses a subtly different data type or something.)
⬤Ｅ⟦⮌θθ⟧

Check the list both backwards and forwards.
✂⮌ι⁰⊟ι¹

Slice the last n elements of the reversed list where n is the last element.
⬤ι∨⁼№ιλ¹⁼λ§ι⁰

Check that each element is either unique or equal to the first element.

Ruby, 64 56 bytes
Mimics the JavaScript answer in that it takes a helper function and checks the array and its reversed version, but the check for uniqueness is done by taking the subarray based on the key, removing all copies of the key, then checking if the (modified) subarray matches its deduplicated version.
-8 bytes by improving the empty list check, and golfing the deduplication code.
->a{g=->f=0,*a{a=a[0,f]-[f];a&a==a};g[*a]&g[*a.reverse]}

Try it online!

Python 3.8 (pre-release), 138 \$\cdots\$ 102 91 bytes
lambda x:all(len(set(t:=[e for e in l[1:l[0]+1]if e-l[0]]))==len(t)for l in[x,x[::-1]]if l)

Try it online!
Saved 11 bytes thanks to @JoKing!!!

Perl 5 -MList::Util=uniq,head -pF,, 71 66 bytes
sub b{(@_=grep$_-@_[0],head$_[0]+1,@_)==uniq@_}$_=b(reverse@F)*b@F

Try it online!

J, 36 28 bytes
*&({.(-:~.)@-.~}.{.~{.<.#)|.

Try it online!

*&(            )|. Take the original input (implicit in the hook) and its reverse |., and multiply the boolean values * produced by transforming them with the verb in parens &(  )

Let's break down the verb in parens...

}.{.~{.<.# From the beheaded }. input take {.~ this many elements: The smaller of <. the first element {. and the length of the list #
{.(  )@-.~ And from that remove all instances of -.~ the first element of the list {. and @ apply the inner verb in parens...
(-:~.) Is the list identical to -: its uniq ~.?

R, 72 71 70 bytes
`-`=function(l)!anyDuplicated(head(l,l[1]+1),l[1])
-(l=scan())&-rev(l)

Try it online!
Saved a byte thanks to Sumner18.

Couldn't you shave a byte by not aliasing x=l[1] and just using head(l,l[1]+1),l[1])?

@Sumner18 why yes I can. Thanks!

@Sumner18 something like this would be possible if the keys were guaranteed to be strictly less than the length of the list.

I contemplated doing just that with the inputs, but I wanted to diversify the inputs a little bit. I can't make the challenge too easy.

05AB1E, 13 bytes
Â‚εć©£®KDÙQ}P

Port of @NickKennedy's Jelly answer, so make sure to upvote him as well!
Try it online or verify all test cases.
Explanation:
Â            # Bifurcate the (implicit) input-string; short for Duplicate & Reverse copy
 ‚           # Pair this reversed input with the duplicated input
  ε          # Map over the inner lists of this pair:
   ć         #  Extract the head; pop and push remainder-list and first item
    ©        #  Store this head in variable `®` (without popping)
     £       #  Leave the first `®` items from the remainder-list
      ®K     #  Remove all `®` (if present)
        DÙ   #  Duplicate this list, and uniquifiy it
          Q  #  And check if it's still the same
  }P         # After the map, check if both were truthy
             # (which is output implicitly as result)

Husk, 13 bytes
S¤&ΓȯS=uΣSx↑↔

Try it online! The function does the k1 test for the both the list and its reverse.