Published
Edited
Dec 8, 2018
Insert cell
Insert cell
centroids = input.split('\n').map(line => line.match(/\d+/g).map(Number))
Insert cell
Insert cell
function manhattanDistance (a, b) {
return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
largestFiniteArea = {
let unboundedCentroids = new Set();
let centroidAreas = {}

for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
// Get the sorted distances from (x, y) to each centroid
const distances = centroids.map(c => [manhattanDistance(c, [x, y]), c]).sort((a, b) => a[0] - b[0]);
// Don't count points equidistance to >1 centroid
if (distances[0][0] !== distances[1][0]) {
centroidAreas[distances[0][1]] = (centroidAreas[distances[0][1]] || 0) + 1;
}

// If a border point is assigned to a centroid, that centroid's region is infinite
if (x === minX || y === minY || x === maxX || y === maxY) {
unboundedCentroids.add(distances[0][1]);
}
}
}
for (const centroid of unboundedCentroids) {
delete centroidAreas[centroid];
}
return Math.max(...Object.entries(centroidAreas).map(e => e[1]));
}
Insert cell
Insert cell
Insert cell
safeCoordinateCount = {
let safeCoordinateCount = 0;
for (let x = minX; x <= maxX; x++) {
for (let y = minY; y <= maxY; y++) {
// Sum point (x, y)'s distance to each centroid
const totalDistance = centroids.map(c => manhattanDistance(c, [x, y])).reduce((sum, n) => sum + n);
if (totalDistance < totalDistanceCap) {
safeCoordinateCount++;
}
}
}
return safeCoordinateCount;
}
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more