Published
Edited
Oct 25, 2019
16 stars
Insert cell
Insert cell
Insert cell
canvas = {
const context = DOM.context2d(1 << n, height * m);
const link = d3.linkVertical().context(context);
context.lineCap = "round";
context.lineJoin = "round";
context.lineWidth = 0.5;
context.globalCompositeOperation = "multiply";
for (let i = 0; i < 1 << n; ++i) {
context.beginPath();
context.strokeStyle = d3.interpolateSpectral(gray2binary(i) / (1 << n));
for (let j = 0, x = reverse(i, n); j < m; ++j) {
link({
source: [gray2binary(reverse(x, n)), height * j],
target: [gray2binary(reverse(x = applyRule(x, n), n)), height * (j + 1)]
});
}
context.stroke();
if (i & 1) yield context.canvas;
}
}
Insert cell
sample = {
const n = 31;
const m = 40;
const size = 10;
const context = DOM.context2d(size * n, size * m);
let x = Math.random() * (1 << n) | 0;
for (let j = 0; j < m; ++j) {
for (let i = 0; i < n; ++i) {
if (x & (1 << i)) {
context.fillRect(i * size, j * size, size, size);
}
}
x = applyRule(x, n);
yield context.canvas;
}
}
Insert cell
function applyRule(input, n) {
let output = 0;
for (let i = 0; i < n; ++i) {
if (rule & (1 << (
(((input >> (i > 0 ? i - 1 : n - 1)) & 1) << 2) |
(((input >> i) & 1) << 1) |
((input >> (i < n - 1 ? i + 1 : 0)) & 1)
))) {
output |= 1 << i;
}
}
return output;
}
Insert cell
function binary2gray(x) {
x = x ^ (x >> 1);
return x;
}
Insert cell
function gray2binary(x) {
x = x ^ (x >> 16);
x = x ^ (x >> 8);
x = x ^ (x >> 4);
x = x ^ (x >> 2);
x = x ^ (x >> 1);
return x;
}
Insert cell
// http://graphics.stanford.edu/~seander/bithacks.html
function reverse(x, n) {
x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);
x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);
x = (x >> 16) | (x << 16);
return x >>> (32 - n);
}
Insert cell
height = 240
Insert cell
n = 10
Insert cell
m = 5
Insert cell
d3 = require("d3-shape@1", "d3-scale-chromatic@1")
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