Created
August 27, 2019 01:16
-
-
Save alistaire47/23cfb34b30a64e460599e6ce0e44e6e4 to your computer and use it in GitHub Desktop.
brodie's challenge
This file contains hidden or 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
alistaire <- function(n){ | |
two_rows <- rep(seq_len(n/2L), each = 4L) | |
out_mat <- matrix(0L, n, n) | |
index_mat <- matrix(seq_len(n), nrow = 2L) | |
for (i in seq_len(n/2L)){ | |
out_mat[index_mat[, i], ] <- two_rows | |
two_rows <- two_rows + 1L | |
} | |
out_mat | |
} | |
alistaire2 <- function(n){ | |
out_mat <- matrix(rep(seq_len(n/2L) - 1L, each = 2L), n, n) | |
index_mat <- matrix(seq_len(n), nrow = 2) | |
for (i in seq_len(n/2L)){ | |
col_indices <- index_mat[, i] | |
out_mat[, col_indices] <- out_mat[, col_indices] + i | |
} | |
out_mat | |
} | |
cody <- function(n) { | |
matrix(rep(seq_len(n/2L), each = 2L), n, n) + | |
t(matrix(rep(seq_len(n/2L) - 1L, each = 2L), n, n)) | |
} | |
cody2 <- function(n) { | |
matrix(rep(seq_len(n/2L), each = 2L), n, n) + | |
matrix(rep(seq_len(n/2L) - 1L, each = 2L), n, n, byrow = TRUE) | |
} | |
baptiste <- function(n) { | |
kronecker(embed(seq_len(n - 1L), n/2L)[, rev(seq_len(n/2L))], | |
matrix(1L, 2L, 2L)) | |
} | |
n <- 5000L | |
times <- bench::mark( | |
alistaire(n), | |
alistaire2(n), | |
baptiste(n), | |
cody(n), | |
cody2(n), | |
min_iterations = 100 | |
) | |
times | |
#> # A tibble: 5 x 13 | |
#> expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time result memory | |
#> <bch:expr> <bch> <bch:> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm> <list> <list> | |
#> 1 alistaire(n) 329ms 368ms 2.72 239MB 1.17 70 30 25.7s <int[… <df[,… | |
#> 2 alistaire2(n) 339ms 357ms 2.78 287MB 1.56 64 36 23.1s <int[… <df[,… | |
#> 3 baptiste(n) 594ms 608ms 1.64 525MB 3.24 34 67 20.7s <dbl[… <df[,… | |
#> 4 cody(n) 417ms 430ms 2.30 286MB 0.893 72 28 31.4s <int[… <df[,… | |
#> 5 cody2(n) 379ms 394ms 2.53 191MB 0.633 80 20 31.6s <int[… <df[,… | |
#> # … with 2 more variables: time <list>, gc <list> | |
ggplot2::autoplot(times) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
n = 10000