ascii_mandelbrot_set.pl 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 03 January 2018
  4. # https://github.com/trizen
  5. # ASCII generation of the Mandelbrot set (+ANSI colors).
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Mandelbrot_set
  8. use 5.020;
  9. use strict;
  10. use experimental qw(signatures);
  11. use Math::GComplex;
  12. use Term::ANSIColor qw(:constants);
  13. my @colors = reverse(
  14. (BLACK), (RED), (GREEN), (YELLOW), (BLUE), (MAGENTA),
  15. (CYAN), (WHITE), (BRIGHT_BLACK), (BRIGHT_RED), (BRIGHT_GREEN), (BRIGHT_YELLOW),
  16. (BRIGHT_BLUE), (BRIGHT_MAGENTA), (BRIGHT_CYAN), (BRIGHT_WHITE),
  17. );
  18. my @chars = ('-', '#', '%', '*', '+', '!', ';', ':', ',', '.');
  19. sub range_map ($value, $in_min, $in_max, $out_min, $out_max) {
  20. ($value - $in_min)
  21. * ($out_max - $out_min)
  22. / ($in_max - $in_min)
  23. + $out_min;
  24. }
  25. sub mandelbrot_set ($z, $I = 400, $L = 2) {
  26. my $n = 0;
  27. my $c = $z;
  28. while (abs($z) < $L and ++$n <= $I) {
  29. $z = $z * $z + $c;
  30. }
  31. return (($I - $n) / $I);
  32. }
  33. for (my $y = 1 ; $y >= -1 ; $y -= 0.05) {
  34. for (my $x = -2 ; $x <= 0.5 ; $x += 0.0315) {
  35. my $num = mandelbrot_set(Math::GComplex->new($x, $y));
  36. my $color_index = sprintf('%.0f', range_map($num, 0, 1, 0, $#colors));
  37. my $char_index = sprintf('%.0f', range_map($num, 0, 1, 0, $#chars));
  38. print($colors[$color_index] . $chars[$char_index]);
  39. }
  40. print "\n";
  41. }
  42. print (RESET);