While browsing Reddit, I came across this page. It's a fun little task. Here's my solution, with lots of fiddly maths to make the circle look as clean as possible.
import sys
r = int(sys.argv[1])
for y in xrange(-r*1.3,r*1.3,2):
for x in xrange(-r*1.3,r*1.3):
sys.stdout.write('#$@%&0*;:,. '[min(abs(r*r - (x*x+y*y))/(r/2), 11)])
print
Circle of r = 10:
,;*0&&&0*;,
,*%$#@%%%%%@#$%*,
,*@#%0;:,...,:;0%#@*,
,0$@0;. .;0@$0,
.*$@0: :0@$*.
,%;. .;%#&,
,%;. .;%#&,
.*$@0: :0@$*.
,0$@0;. .;0@$0,
,*@#%0;:,...,:;0%#@*,
,*%$#@%%%%%@#$%*,
,;*0&&&0*;,
r = 30:
.,:;*00&&&&&&&00*;:,.
,;0&@$##$@@%%%%%%%@@$##$@&0;,
.;0%$#$%&*;:,,.. ..,,:;*&%$#$%0;.
:0%#$%0;:. .:;0%$#%0:
.;&$#%0;, ,;0%#$&;.
;&$$%*, ,*%$$&;
,0@#%*, ,*%#@0,
;@0: :0@#&;
;%#%*, ,*%#%;
;%#%;. .;%#%;
:%*. .*%#&:
,0$@*, ,*@$0,
;%#&: :%;
,0$@*, ,*@$0,
:%;. .;%#&:
:%; ;%#&:
:%; ;%#&:
:%;. .;%#&:
,0$@*, ,*@$0,
;%#&: :%;
,0$@*, ,*@$0,
:%*. .*%#&:
;%#%;. .;%#%;
;%#%*, ,*%#%;
;@0: :0@#&;
,0@#%*, ,*%#@0,
;&$$%*, ,*%$$&;
.;&$#%0;, ,;0%#$&;.
:0%#$%0;:. .:;0%$#%0:
.;0%$#$%&*;:,,.. ..,,:;*&%$#$%0;.
,;0&@$##$@@%%%%%%%@@$##$@&0;,
.,:;*00&&&&&&&00*;:,.
The explanation I posted on Reddit (sorry about the formatting, hopefully it's still clear).
I guess I should explain what this does. Like the challenge poster, I use the Pythagorean theorem. I look through each coordinate in a square of size 2.6r * 2.6r around the centre-point. The circle only really exists in the 2r * 2r square around the point, but the extra padding on all sides allows for the anti-aliasing to continue further along the edges.
Mathematically, a circle consists of the coordinates (x, y) that satisfy x2 + y2 = r2, r being the radius of the circle. Any points we encounter that satisfy this should be "coloured in" as dark as possible. Some points do not fall exactly on the circle, but they fall close to the circle: the (absolute) difference between r2 and x2 + y2 is (if I am not mistaken) the distance between (x,y) and the closest point on the circle to (x,y). If the difference is 0, we have the case above. Otherwise, the larger the value, the less it is part of the circle and so the lighter we should 'colour' it.
To colour points, I index the 'colouring' string by a scaled value of this closeness, scaled so the width of the ring remains the same for different values of r.
No comments:
Post a Comment