Last active
August 7, 2017 22:19
-
-
Save Demonstrandum/33b89f64b97b1a9bf9932a63a6650078 to your computer and use it in GitHub Desktop.
Mandelbrot Fractal in ASCII
This file contains 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
#!/usr/bin/env ruby | |
height = %x{ tput lines }.to_i - 3 # -3 for PS1 | |
width = %x{ tput cols }.to_i | |
scale = 0.6 * width.to_f / height.to_f | |
definition = 40 | |
def calculate a, b, c_arr | |
ca, cb = c_arr | |
left = a * a - b * b | |
right = 2 * a * b | |
a = left + ca | |
b = right + cb | |
[a, b] | |
end | |
fractal = String.new | |
shade = [" ", ".", ":", "-", "~", "^", "•", "=", "&", "£", "$", "#", "@"] | |
height.times do |y| | |
width.times do |x| | |
a = ca = (x * 2 * scale / width - scale) - 0.5 | |
height_scale = 2 * scale * height.to_f / width.to_f # x2 for centering | |
b = cb = y * 2 * height_scale / height - height_scale | |
snap = 0 | |
until snap >= definition | |
a, b = calculate(a, b, [ca, cb]) | |
break if a * a + b * b > 16 | |
snap += 1 | |
end | |
unless snap == definition | |
fractal << shade[snap * (shade.size - 1) / definition] | |
else | |
fractal << shade[-1] # Max iteration is set to black (the inner body part) | |
end | |
end | |
fractal += "\n" | |
end | |
print fractal |
Author
Demonstrandum
commented
Aug 7, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment