Sometimes proclaimed as the oldest algorithm put down on paper, Euclid's
algorithm is enthralling in its recursive simplicity.

Euclid's version used a minus instead of a modulo (%), but
otherwise here it is in its full glory.

gcd = (n, m) => m ? gcd(m, n % m) : n

Euclidean rhythms

At the surface level it is calculating the GCD, the largest number that divides
both n and m. But really it is unravelling a number pair.

In 2005, Godfried Toussaint realized that Euclid's algorithm encodes many drum
beats. For example, here is how E(3, 8) sounds.

Code

Here is an implementation of the algorithm described by Toussaint.

const E = (k, n) => {
let s = Array(n).fill()
.map((_, i) => (i < k ? [1] : [0]))
let d = n - k
n = Math.max(k, d)
k = Math.min(k, d)
let z = d
while (z > 0 || k > 1) {
for (let i = 0; i < k; i++)
s[i].push(...s[s.length - 1 - i])
s.splice(-k)
z = z - k
d = n - k
n = Math.max(k, d)
k = Math.min(k, d)
}
return s.flat()
};

At each step, we "fold" the end of the sequence into the beginning. How much to
fold is given by the value of gcd(n, m) at that step.

When we call this function with two numbers (the number of 1's, and
the length of the sequence), it returns a sequence where the 1's are
maximally displaced. e.g. if you copy paste this code to your browser's
developer tools, and then call E(3, 8), you'll get

> E(3, 8)
[1, 0, 0, 1, 0, 0, 1, 0]

Surprisingly, this function is all we need to replicate many real world rhythms.
All we need is a way to convert the ones into sound, like how we did
with the player above, which produced a beep each time it found a one in the
E(3, 8) sequence.

Here is a player that cycles through various Euclidean rhythms.

I have listened to this for hours.

Not just beats

It is customary to use Euclidean rhythms to trigger onsets of beats, but there
is nothing stopping us from using it for other purposes, as a generic organic
pattern.

Here we use it to accent certain notes by using a different attack and release.

Everything at once

And we can do all these at once. The integral framework provided by Euclidean
rhythms ensures that the mismash doesn't sound as chaotic as mixing arbitrary
patterns would've. It might even sound nice to some.