Created
February 26, 2025 16:21
-
-
Save andrewstellman/b66f8df263e339879f783e5569294c6c to your computer and use it in GitHub Desktop.
Generate a console Mandelbrot in C#
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
int width = 80; // Default width | |
if (args != null && args.Length > 0) | |
{ | |
if (int.TryParse(args[0], out int parsedWidth) && parsedWidth > 0) | |
{ | |
width = parsedWidth; | |
} | |
} | |
int height = width / 2; | |
double xMin = -2.0; | |
double xMax = 1.0; | |
double yMin = -1.0; | |
double yMax = 1.0; | |
int maxIterations = 100; | |
for (int row = 0; row < height; row++) | |
{ | |
for (int col = 0; col < width; col++) | |
{ | |
double x0 = xMin + (xMax - xMin) * col / width; | |
double y0 = yMin + (yMax - yMin) * row / height; | |
double x = 0; | |
double y = 0; | |
int iteration = 0; | |
while (x*x + y*y < 4 && iteration < maxIterations) | |
{ | |
double xTemp = x*x - y*y + x0; | |
y = 2*x*y + y0; | |
x = xTemp; | |
iteration++; | |
} | |
// Choose a character based on how quickly the point escaped | |
char displayChar = ' '; | |
if (iteration == maxIterations) | |
displayChar = '#'; // Point is in the set | |
else if (iteration > maxIterations * 0.75) | |
displayChar = '@'; | |
else if (iteration > maxIterations * 0.5) | |
displayChar = '*'; | |
else if (iteration > maxIterations * 0.25) | |
displayChar = '+'; | |
else if (iteration > maxIterations * 0.1) | |
displayChar = '.'; | |
Console.Write(displayChar); | |
} | |
Console.WriteLine(); | |
} |
Author
andrewstellman
commented
Feb 26, 2025

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment