0
\$\begingroup\$

I am trying to find a more efficient way to print the number of descents in a permutation using R as my programming language. This code does it for the numbers 3 to 10:

# this function finds the number of descents in a permutation
numberOfDescents <- function(prm) {
  descents <- 0

  for(i in seq_len(nrow(prm))) {
    for(j in seq_len(ncol(prm))) {
      if(j+1 < ncol(prm) && prm[i,j] > prm[i,j+1]) {
        descents <- descents + 1
      }
    }
  }

  return(descents)
}

for(size in 3:10) {
  prm <- gtools::permutations(n=size, r=size, 1:size)
  print(numberOfDescents(prm))
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You do not have to loop over the rows and columns for this, and compare the matrix of all columns except the last two with all those values a column further. It only becomes slow now for the time it takes to generate your permutations. But if you look at the benchmark on just the descent functions you can speed up a factor 12.

fastnumberOfDescents <- function(prm) {
  size <- ncol(prm)
  descents <- sum(unlist(as.list(prm[, 1:(size-2)] > prm[, 2:(size-1)])))
  return(descents)
}

for(size in 3:10) {
  prm <- gtools::permutations(n=size, r=size, 1:size)
  print(fastnumberOfDescents(prm))
}

# [1] 3
# [1] 24
# [1] 180
# [1] 1440
# [1] 12600
# [1] 120960
# [1] 1270080
# [1] 14515200

Benchmark

Here a speed test for size <- 10 and note that I kept the generation of prm10 out of the benchmark. Just to see the gain in speed on finding the descents.

size <- 10
prm10 <- gtools::permutations(n=size, r=size, 1:size)

library(rbenchmark)

benchmark(
  "fastnumberOfDescents" = { fastnumberOfDescents(prm10) },
  "numberOfDescents" = { numberOfDescents(prm10) },
  replications = 5,
  columns = c("test", "replications", "elapsed", "relative")
)

#                   test replications elapsed relative
# 1 fastnumberOfDescents            5    8.87    1.000
# 2     numberOfDescents            5  109.20   12.311
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.