Polya's urn
Black and white balls. Moving.
HTML
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg id="figure" viewBox="0 0 300 50" style="background-color: papayawhip; border-radius: 1rem" xmlns="http://www.w3.org/2000/svg"></svg>
JavaScript
let N = 5;
let r = 5;
let s = 2;
let data = d3.range(2 * N);
d3.select("#figure")
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", (_, i) =>
i < N ? (i + 1) * (2 * r + s) : 300 - (i - N + 1) * (2 * r + s)
)
.attr("cy", 26)
.attr("r", r)
.attr("stroke", "blue")
.attr("fill", d => (d < N ? "white" : "black"));
update(data);
function update(data) {
let I = data.slice(0, N);
let J = data.slice(N, 2 * N);
let i = randInt(N);
let x = I[i];
let j = randInt(N);
let y = J[j];
let newData = [
...I.slice(0, i),
...I.slice(i + 1),
y,
...J.slice(0, j),
...J.slice(j + 1),
x
];
d3.select("#figure")
.selectAll("circle")
.data(newData, d => d)
.transition()
.duration(3000)
.attr("cx", (_, i) =>
i < N ? (i + 1) * (2 * r + s) : 300 - (i - N + 1) * (2 * r + s)
)
.end()
.then(() => update(newData));
}
function randInt(n) {
return Math.floor(Math.random() * n);
}