logoalt Hacker News

ventanayesterday at 11:22 PM2 repliesview on HN

I don't believe you need trig for that, it actually makes it harder if you try to iterate the angle. I believe the expected solution is to start at (R, 0) which is known belongs to the circle, and go left/top, choosing the pixel closest to the circle on each step, which does not require any floating point arithmetic.


Replies

HarHarVeryFunnytoday at 12:21 AM

The problem is under-specified both in terms of requirements and any implementation restrictions.

Given the lack of difficulty of the other questions (and this being pre-internet, targeted for an intern), I don't think the interviewer can have been expecting too much sophistication.

The other obvious way do do it, only requiring the same minimal realization that this is about triangles (with radius as hypotenuse) is to use r^2 = x^2 + y^2 and iterate x=0..r deriving y. You could do it without sqrt if they stipulated that.

vikingeriktoday at 12:44 AM

Right, iterating through pixels is better. The tricky part about iterating the angle is that you need to choose the step size correctly or else you could skip pixels. Like if you iterate in 1-degree increments, you'll plot 360 pixels total, but the size of the circle on your canvas might be more than 360 pixels wide. I'm sure there's a way to choose the angle iteration step size to guarantee not skipping pixels, but you'd often duplicate work and re-plot the same pixel twice.

So yes, start at (R, 0), increment the y-coordinate each time and possibly decrement the x-coordinate, until x=y which will be at 45°. If the circle's center is an integer on the pixel grid, you can reflect/translate each pixel in that first octant to all eight as you go. If the center is fractionally positioned, you'd have to calculate it all the way around, iterating primarily on y or x depending on the location.

show 1 reply