Skip to content

Instantly share code, notes, and snippets.

@andrie
Created July 17, 2023 10:23
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 andrie/a4f34416baf9e8a6cab68458709fc7d2 to your computer and use it in GitHub Desktop.
Save andrie/a4f34416baf9e8a6cab68458709fc7d2 to your computer and use it in GitHub Desktop.
Compute the hilbert curve using R
# compute hilbert curve
# inspired by https://logicgrimoire.wordpress.com/2020/06/19/how-to-draw-the-hilbert-curve-using-a-computer-program/
library(ggplot2)
library(dplyr)
library(magrittr)
# rotate matrix
rotate <- function(x, th = pi/2) {
x %*% matrix(c(cos(th), -sin(th), sin(th), cos(th)), ncol = 2, byrow = TRUE)
}
# reflect matrix
reflect <- function(x) {
x[, 1] <- -x[, 1]
x
}
# translate matrix
translate <- function(x, v) {
sweep(x, 2, v, `+`)
}
# compute hilbert curve
hilbert <- function(h, depth = 1) {
if (depth == 0) return(h)
h <- h * 0.5
h <- rbind(
translate(reflect(rotate(h, -pi/2)) , c(-0.5, -0.5)),
translate( h , c(-0.5, 0.5)),
translate( h , c( 0.5, 0.5)),
translate(reflect(rotate(h, pi/2)) , c( 0.5, -0.5))
)
hilbert(h, depth - 1)
}
# initialise matrix
h <- matrix(c(0, 0), ncol = 2, dimnames = list(NULL, c("x", "y")))
# compute and plot
hilbert(h, 3) %>%
as_tibble() %>%
mutate(n = seq(nrow(.))) %>%
ggplot(aes(x, y, aes(colour = n))) +
geom_path(aes(colour = n)) +
scale_colour_gradient(low = "red", high = "blue")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment