Skip to content

Instantly share code, notes, and snippets.

@creaktive
Created December 31, 2018 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creaktive/eab9bd55ee9c64686af91a94a02b8caf to your computer and use it in GitHub Desktop.
Save creaktive/eab9bd55ee9c64686af91a94a02b8caf to your computer and use it in GitHub Desktop.
Recursive Hilbert Curve generator
#!/usr/bin/env perl
# http://www.fundza.com/algorithmic/space_filling/hilbert/basics/
# http://www.soc.napier.ac.uk/~andrew/hilbert.html
use strict;
use warnings;
sub hilbert {
my ($n, $x, $y, $xi, $xj, $yi, $yj, $mn) = (@_, qw(0 0 1) x 2, $_[0]);
return !$n
? [
map { (2 ** $mn) * $_ - 0.5 }
($y + ($yi + $xi)/2, $x + ($yj + $xj)/2)
] : (
hilbert($n-1, $x, $y, $yi/2, $yj/2, $xi/2, $xj/2, $mn),
hilbert($n-1, $x+$xi/2, $y+$xj/2 , $xi/2, $xj/2, $yi/2, $yj/2, $mn),
hilbert($n-1, $x+$xi/2+$yi/2, $y+$xj/2+$yj/2, $xi/2, $xj/2, $yi/2, $yj/2, $mn),
hilbert($n-1, $x+$xi/2+$yi, $y+$xj/2+$yj, -$yi/2,-$yj/2, -$xi/2, -$xj/2, $mn),
);
}
printf "%d,%d\n", @$_ for hilbert($ARGV[0] || 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment