Gamified challenge · K-means clustering
points[i] = [x, y] are tents (whole numbers 0-100) and centroids[j] = [x, y] are the starting flags. Assign every point to the centroid with the smallest squared distance ((x − cx)² + (y − cy)²), ties going to the lower index. Then update every centroid to the exact mean of its points (a centroid with no points stays where it is). Keep alternating until an assignment step changes nothing.
Write kmeans(points, centroids) returning the final cluster index of every point, in order. Keep means exact: store a centroid as (sumX, sumY, count) and compare d₁ / n₁² < d₂ / n₂² as d₁ · n₂² < d₂ · n₁² with d = (n·x − sumX)² + (n·y − sumY)² (use long in Java).
Example: points [[1,1],[2,1],[1,2],[8,8],[9,8],[8,9],[5,5]], centroids [[0,0],[10,10]] gives [0, 0, 0, 1, 1, 1, 0]: (5, 5) is exactly halfway at first, so it joins centroid 0, and stays there after the means move.
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google