Published
Edited
Nov 17, 2021
1 star
Insert cell
Insert cell
Insert cell
function euclid(l, s) {
if (s > l) throw new Error("l must be larger than s");
if (s == 0) return l;
return euclid(s, l % s);
}
Insert cell
euclid(25, 15)
Insert cell
euclid(861, 126)
Insert cell
Insert cell
function statefulEuclid(l, s, results = []) {
if (s > l) throw new Error("l must be larger than s");
results.push([l, s]);
if (s == 0) return results;
return statefulEuclid(s, l % s, results);
}
Insert cell
statefulEuclid(25, 15)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
JSON.stringify(statefulEuclid(8, 5))
Insert cell
Insert cell
function euclidean(on, off) {
// create initial pattern
// e.g. ["1", "1", "0", "0", "0"]
let pattern = new Array(on).fill("1").concat(new Array(off).fill("0"));

let indexOfDiff;
while (indexOfDiff != -1) {
// split into two
// e.g. ["1", "1"] and ["0", "0", "0"]
let remainder = pattern.splice(indexOfDiff);

// merge the two together
// e.g. ["10", "10"]
pattern = pattern
.map((sequence, i) => sequence + (remainder[i] || ""))
// concat any remainder
// e.g. ["10", "10", "0"]
.concat(remainder.slice(indexOfDiff));

// see if there's still multiple sequences and if they're unique
// if so, loop
indexOfDiff = pattern.findIndex((sequence) => sequence != pattern[0]);
}

return pattern.join("");
}
Insert cell
Insert cell
euclidean(4, 0)
Insert cell
euclidean(4, 8)
Insert cell
euclidean(5, 8)
Insert cell
Insert cell
function modulatePattern(pattern, amount = 1) {
// negate amount so that positive modulation shifts to the right
return pattern.slice(-amount) + pattern.slice(0, -amount);
}
Insert cell
// example usage
modulatePattern("10", 1) === "01"
Insert cell
// compare our pattern to Toussaint's
modulatePattern("1001010010010", 5) === "1001010010100"
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more