pascal-fibonacci_triangle.pl 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 25 March 2019
  4. # https://github.com/trizen
  5. # Generate a visual representation of the Pascal-Fibonacci triangle.
  6. # Definition by Elliott Line, Mar 22 2019:
  7. # Consider a version of Pascal's Triangle: a triangular array with a single 1 on row 0,
  8. # with numbers below equal to the sum of the two numbers above it if and only if that sum
  9. # appears in the Fibonacci sequence. If the sum is not a Fibonacci number, `1` is put in its place.
  10. # OEIS sequence:
  11. # https://oeis.org/A307069
  12. use 5.010;
  13. use strict;
  14. use warnings;
  15. use Imager qw();
  16. use ntheory qw(is_square);
  17. use experimental qw(signatures);
  18. sub is_fibonacci($n) {
  19. my $m = 5 * $n * $n;
  20. is_square($m - 4) or is_square($m + 4);
  21. }
  22. my $size = 1000; # the size of the triangle
  23. my $img = Imager->new(xsize => $size, ysize => $size);
  24. my $black = Imager::Color->new('#000000');
  25. my $red = Imager::Color->new('#ff00000');
  26. $img->box(filled => 1, color => $black);
  27. sub pascal_fibonacci {
  28. my ($rows) = @_;
  29. my @row = (1);
  30. foreach my $n (1 .. $rows - 1) {
  31. my $i = 0;
  32. my $offset = ($rows - $n) / 2;
  33. foreach my $elem (@row) {
  34. $img->setpixel(
  35. x => $offset + $i++,
  36. y => $n,
  37. color => {
  38. hsv => [$elem == 1 ? 0 : (360 / sqrt($elem)), 1 - 1 / $elem, 1 - 1 / $elem]
  39. }
  40. );
  41. }
  42. if ($n <= 10) {
  43. say "@row";
  44. }
  45. #<<<
  46. @row = (1, (map {
  47. my $t = $row[$_] + $row[$_ + 1];
  48. is_fibonacci($t) ? $t : 1;
  49. } 0 .. $n - 2), 1);
  50. #>>>
  51. }
  52. }
  53. pascal_fibonacci($size);
  54. $img->write(file => "pascal_fibonacci_triangle.png");