Little useless-useful R functions – Return matrix elements in spiral order
This article is originally published at https://tomaztsql.wordpress.com
Another one from the Leetcode challenge. This time, get the elements (single values) from the matrix in a spiral order with a starting position of [1,1].
So, the basic idea is to retrieve a vector of elements from a matrix in the following order:
In this order, we get the vector with the following elements:
So, we need to create the boundaries, count the rows | columns and return a vector of elements. Here is the useless function:
## return elements from matrix in spiral order
matrix_spiral <- function(mat) {
mr <- dim(mat)[1]
nc <- dim(mat)[2]
total_len <- mr*nc
#path #TRUE -> visited; FALSE -> unvisited
visit <- matrix(FALSE, nrow=mr, ncol=nc)
#helper variables
gor <- 1
dol <- mr
levo <- 1
desno <- nc
res <- vector()
while (length(res) < total_len) {
for (i in levo:nc) {
if (!visit[gor, i]) {
res <- c(res, mat[gor,i])
visit[gor, i] <- TRUE
} }
gor <- gor + 1
for (i in gor:mr) {
if (!visit[i, desno]) {
res <- c(res, mat[i,desno])
visit[i, desno] <- TRUE
} }
desno <- desno - 1
if (gor <= dol) {
for (i in desno:levo) {
if (!visit[dol, i]) {
res <- c(res, mat[dol,i])
visit[dol, i] <- TRUE
} }
dol <- dol - 1
}
if (levo <= desno) {
for (i in dol:gor) {
if (!visit[i, levo]) {
res <- c(res, mat[i,levo])
visit[i, levo] <- TRUE
} }
levo <- levo + 1
} }
return(res)
}
As always, the complete code is available on Github in Useless_R_function repository. The sample file in this repository is here (filename: Spiral_matrix.R). Check the repository for future updates.
Happy R-coding and stay healthy!
Thanks for visiting r-craft.org
This article is originally published at https://tomaztsql.wordpress.com
Please visit source website for post related comments.