Skip to content

Instantly share code, notes, and snippets.

@lucaschen
Created March 17, 2018 11:55
Show Gist options
  • Save lucaschen/c8cae6921db8d6132f7a2d922bce737d to your computer and use it in GitHub Desktop.
Save lucaschen/c8cae6921db8d6132f7a2d922bce737d to your computer and use it in GitHub Desktop.
Drawing an ASCII circle
const drawASCIICircle = radius => {
// x^2 + y^2 = radius^2 draws a circle
const expectedValue = radius ** 2;
// imagine a graph with the centre of a circle right on point (0, 0)
for (let y = -radius; y <= radius; y++) {
// y first, because we go across before we go down (inner loop runs more often)
for (let x = -radius; x <= radius; x++) {
const computedValue = x ** 2 + y ** 2;
// use radius to get a roughly single-thickness circle - double or halve this for corresponding results
if (Math.abs(computedValue - expectedValue) <= radius) {
process.stdout.write("*");
} else {
process.stdout.write(" ");
}
}
process.stdout.write("\n");
}
};
drawASCIICircle(10); // draws circle of radius 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment