Created
January 5, 2023 22:45
-
-
Save n8allan/9d3ed8beda9764e695b353f418b3479c to your computer and use it in GitHub Desktop.
Concentric circle generation with no gaps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class Concentric | |
{ | |
/// <summary> Enumerates the rings of a circle starting from 1 radius up to the given radius. </summary> | |
public static IEnumerable<Point> EnumerateConcentric(int centerX, int centerY, int radius) | |
{ | |
yield return new Point(centerX, centerY); | |
for (var r = 1; r <= radius; ++r) | |
foreach (var point in EnumerateRadius(centerX, centerY, r)) | |
yield return point; | |
} | |
/// <summary> Enumerates the boundary of a circle at the given radius. </summary> | |
public static IEnumerable<Point> EnumerateRadius(int centerX, int centerY, int radius) | |
{ | |
// based on Tony Barrera's "4-connected" circle algorithm (gapless fast concentric circles) | |
int determinant = -(radius >> 1); | |
int x = 0; | |
int y = radius; | |
do | |
{ | |
yield return new Point(centerX + x, centerY + y); | |
yield return new Point(centerX + x, centerY - y); | |
yield return new Point(centerX - x, centerY + y); | |
yield return new Point(centerX - x, centerY - y); | |
yield return new Point(centerX + y, centerY + x); | |
yield return new Point(centerX + y, centerY - x); | |
yield return new Point(centerX - y, centerY + x); | |
yield return new Point(centerX - y, centerY - x); | |
if (determinant <= 0) | |
{ | |
++x; | |
determinant += x; | |
} | |
else | |
{ | |
--y; | |
determinant -= y; | |
} | |
} while (x <= y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment