Skip to content

Commit

Permalink
Shorter solution
Browse files Browse the repository at this point in the history
  • Loading branch information
w8r committed Jun 21, 2024
1 parent f45a98b commit 2c778bf
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 19 deletions.
25 changes: 7 additions & 18 deletions src/pack/enclose.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,16 @@ export default function(circles) {
export function packEncloseRandom(circles, random) {
var i = 0, n = (circles = shuffle(Array.from(circles), random)).length, B = [], p, e;

var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE;
var maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
for (var k = 0; k < n; ++k) {
var c = circles[k];
minX = Math.min(minX, c.x - c.r);
minY = Math.min(minY, c.y - c.r);
maxX = Math.max(maxX, c.x + c.r);
maxY = Math.max(maxY, c.y + c.r);
}

var cx = (minX + maxX) / 2, cy = (minY + maxY) / 2;

while (i < n) {
p = circles[i];
if (e && enclosesWeak(e, p)) ++i;
else e = encloseBasis(B = extendBasis(B, p, cx, cy), cx, cy), i = 0;
else e = encloseBasis(B = extendBasis(B, p)), i = 0;
}

return e;
}

function extendBasis(B, p, cx, cy) {
function extendBasis(B, p) {
var i, j;

if (enclosesWeakAll(p, B)) return [p];
Expand All @@ -48,7 +36,7 @@ function extendBasis(B, p, cx, cy) {
if (enclosesNot(encloseBasis2(B[i], B[j]), p)
&& enclosesNot(encloseBasis2(B[i], p), B[j])
&& enclosesNot(encloseBasis2(B[j], p), B[i])
&& enclosesWeakAll(encloseBasis3(B[i], B[j], p, cx, cy), B)) {
&& enclosesWeakAll(encloseBasis3(B[i], B[j], p), B)) {
return [B[i], B[j], p];
}
}
Expand Down Expand Up @@ -77,11 +65,11 @@ function enclosesWeakAll(a, B) {
return true;
}

function encloseBasis(B, cx, cy) {
function encloseBasis(B) {
switch (B.length) {
case 1: return encloseBasis1(B[0]);
case 2: return encloseBasis2(B[0], B[1]);
case 3: return encloseBasis3(B[0], B[1], B[2], cx, cy);
case 3: return encloseBasis3(B[0], B[1], B[2]);
}
}

Expand All @@ -105,7 +93,8 @@ function encloseBasis2(a, b) {
};
}

function encloseBasis3(a, b, c, cx, cy) {
function encloseBasis3(a, b, c) {
var cx = (a.x + b.x + c.x) / 3, cy = (a.y + b.y + c.y) / 3;
var x1 = a.x - cx, y1 = a.y - cy, r1 = a.r,
x2 = b.x - cx, y2 = b.y - cy, r2 = b.r,
x3 = c.x - cx, y3 = c.y - cy, r3 = c.r,
Expand Down
2 changes: 1 addition & 1 deletion test/pack/enclose-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ it("packEnclose(circles) handles a tricky case", () => {
]),
{
r: 20.790781637717117,
x: 12.80193548387097,
x: 12.801935483870967,
y: 61.59615384615385
}
);
Expand Down

0 comments on commit 2c778bf

Please sign in to comment.