Article 78QWG CodeSOD: Quite a Distance from the Right Solution

CodeSOD: Quite a Distance from the Right Solution

by
Remy Porter
from The Daily WTF on (#78QWG)

Fritz's team needed to see if one point was within a certain distance from a center point. You or I would likely try and answer this question using a simple distance calculation, since that's the question we're trying to answer. But what if you didn't understand distances at all? Then you could write this little piece of genius.

 private bool IsWithin(Point point, int radius) { for (int x = -radius; x < radius + 1; x++) { for (int y = -radius; y < radius + 1; y++) { if ((PositionX == point.X + x) && (PositionY == point.Y + y)) return true; } } return false; }

This limits us to integer point values, which itself is fine. This iterates across every coordinate from (x-radius,y-radius) to (x+radius,y+radius) and checks if any of them are equal to our center point, (PositionX,PositionY). Notably, this means we're not checking a radius, at least not in a traditional metric, we're checking a box (or using the taxicab metric). Which if we wanted to check a box, we actually have even easier math than the distance equation- we could do that with pure bounds checking.

I've never thought to try and brute force distance checking, and that feels like a failure of my own creativity. Fritz's team mate at least was able to WTF in a way I wouldn't have considered.

proget-icon.png [Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments