pts = [
{id: 1, x: 1, y: 1}, {id: 2, x: 1, y: 2}, {id: 3, x: 2, y: 1},
{id: 4, x: 8, y: 8}, {id: 5, x: 9, y: 8}, {id: 6, x: 8, y: 9}
];
// Precompute the steps
cents0 = [{x: 1, y: 1, c: "0"}, {x: 2, y: 2, c: "1"}];
asgn0 = pts.map(p => ({...p, c: "-1"}));
asgn1 = pts.map(p => {
let d0 = Math.hypot(p.x - cents0[0].x, p.y - cents0[0].y);
let d1 = Math.hypot(p.x - cents0[1].x, p.y - cents0[1].y);
return {...p, c: d0 < d1 ? "0" : "1"};
});
cents1 = cents0;
cents2 = [
{x: (1+1+2)/3, y: (1+2+1)/3, c: "0"},
{x: (8+9+8)/3, y: (8+8+9)/3, c: "1"}
];
asgn2 = asgn1;
asgn3 = pts.map(p => {
let d0 = Math.hypot(p.x - cents2[0].x, p.y - cents2[0].y);
let d1 = Math.hypot(p.x - cents2[1].x, p.y - cents2[1].y);
return {...p, c: d0 < d1 ? "0" : "1"};
});
cents3 = cents2;
currentAsgn = [asgn0, asgn1, asgn2, asgn3][step];
currentCents = [cents0, cents1, cents2, cents3][step];
Plot.plot({
width: 700,
height: 700,
grid: true,
x: {domain: [0, 10]},
y: {domain: [0, 10]},
marks: [
Plot.dot(currentAsgn, {x: "x", y: "y", fill: d => d.c === "-1" ? "gray" : (d.c === "0" ? "#1f77b4" : "#ff7f0e"), r: 10, stroke: "white", strokeWidth: 1}),
Plot.dot(currentCents, {x: "x", y: "y", fill: d => d.c === "0" ? "#1f77b4" : "#ff7f0e", r: 16, symbol: "star", stroke: "black", strokeWidth: 1.5})
]
})