Math + Code = Art: A Miraculous Centrifuge One-Liner

Cover Image for Math + Code = Art: A Miraculous Centrifuge One-Liner
William Forty
William Forty

Every so often you're chewing on a coding problem and something pops out fully formed that you didn't really earn. You stare at it, double-check it works, and then sit with the slightly uncomfortable feeling that the universe handed you something tidier than the work warranted. The balancing-a-centrifuge problem on Codewars gave me one of those.

The setup is dry enough. You're given an array of zeros and ones representing the holes of a centrifuge — 0 for empty, 1 for a test tube. All holes are evenly spaced around a circle and equidistant from the centre. Return true if the arrangement is balanced — i.e. the centre of mass of the tubes sits on the centre of the centrifuge.

The obvious approach

Your first instinct is right, and most submissions on the leaderboard stop there. Treat each tube as a unit vector pointing from the centre out to its hole. Sum the vectors. If you end up back at the origin, it's balanced.

In code, that means: map each index to an angle (2π × (i / n)), keep the ones where the slot is occupied, sum the cos and sin components separately, then check that the hypotenuse of the resulting (x, y) is close to zero — close, not equal, because floating point.

Totally sane. Passes. I submitted it. Then I started picking at it.

The first squeeze was packing x and y into one number by scaling one of them — multiply x by 1000, add y, sum the lot, check the result is close to zero. The 1000 is a separator wide enough that no plausible sum of coss spills into the sin band. Smaller separators worked sometimes; at very small separators, harmonics between the cos and sin terms started faking balanced answers when the centrifuge wasn't.

That's the moment the interesting question came into view. The reason small separators fail isn't an off-by-one bug. It's that for rational fractions of a circle, the deflections in the two axes are coupled in ways that conspire to cancel by coincidence. Which then made me wonder: can I use that — or rather, weaponise its opposite?

The actual approach

Forget two axes. Pick one. Look only at the y-deflection (the sine).

Each tube contributes sin(2π × i / n). The angle is a rational multiple of . For any rational multiple of , there's always another rational multiple of whose sine is the exact negative of the first — that's why the naive vector sum cancels for balanced inputs and is also why you can get spurious cancellations on a single axis. Different positions can produce the same sine.

Now nudge every angle by an irrational offset. Suddenly each tube's contribution is the sine of (rational + irrational), which is itself irrational. And the only way to cancel an irrational value s is with -s. You cannot construct -s by summing other sines of (different rational + same irrational) terms, because that would require the rationals to combine into something that flips the irrational part — and rationals can't do that. The only way the y-sum hits zero is if the contributions genuinely pair up around the circle. Which is exactly the definition of balanced.

So you collapse the whole problem onto one axis, and the irrational offset guarantees no false positives.

Here's the one-liner:

const isBalanced = c => Math.abs(c.reduce((a, t, i) => a + t * Math.sin(1 + 2 * Math.PI * i / c.length), 0)) < 1e-9;

The 1 + inside the sine is the irrational offset. I originally reached for Euler's number e there, on the grounds that I needed an irrational. Then I noticed I was already inside Math.sin(... 2π ...)π is right there. Adding a plain rational 1 to an angle that's already an irrational multiple of π is, in effect, putting a rational inside an irrational context rather than the other way round. Same guarantee, one fewer constant. The t * zeroes out empty holes. The 1e-9 absorbs the floating point dust.

Why irrationality is doing the work

It's tempting to file this under "neat trick with e" but the constant is incidental. The load-bearing property is that the offset is incommensurable with the lattice of angles the centrifuge can produce. You're picking a value that the problem's own arithmetic provably cannot manufacture on its own. That makes any cancellation in the final sum unambiguous: it can only come from genuine pairwise balance, not from a numerical coincidence.

Almost every trick I've collected over the years lives in one of two categories. The first is the obvious one — spot a redundant operation, remove it. Cache something. Memoise. Reorder a loop. Pick a better data structure. These are improvements within the structure of the solution you already have.

This one is in a different category. You don't optimise the check. You change the values so that the check becomes trivial. The constraint — "no rational combination can fake balance" — gets encoded into the data itself, not enforced by a separate test. Once the values carry the property, the verification collapses to "is this number zero?".

That category is rarer and a lot more fun to find. It's the same family of move as using a prime modulus to make collisions vanish, or laying out a grid so that a single bitwise AND tells you adjacency. Pick your representation carefully enough and the algorithm stops needing to be clever.

The centrifuge problem looks like geometry. The solution turned out to be number theory wearing a lab coat. That's the bit that felt like art.