Study notes 1

numSeq <- c(0:9)
n <- 1e6

# Gets the nth lexicographical permutation of the given sequence.
GetNthLexPermutation <- function(sequence, n) {
  len <- length(sequence)  # Calculate the length of the sequence.
  
  # Check if n is within the total number of permutations.
  if (n > prod(1:len) | n < 1) {
    stop("The number required is outside the number of possible permutations.")
  } else {
    nth <-
      numeric(len)  # Create a vector called nth of length len to store the nth permutation.
    
    # Go through each place in the vector nth and work out what character belongs there.
    for (i in 1:(len - 1)) {
      # We change n each time, when it is 0 we want the last character in what is left of the sequence.
      if (n == 0) {
        nth[i] <- sequence[length(sequence)]
      } else {
        # The next character is given by the (n-1)/(total number of permutations) position in the remaining sequence.
        tmp <- prod(1:(len - i))
        div <- floor((n - 1) / tmp)
        nth[i] <- sequence[div + 1]
      }
      
      n <-
        n %% tmp  # Change n to be n mod tmp (we have found the first few characters that start
      # the nth permutation, so we are looking for the remaining characters which is the (n mod tmp)th
      # permutation of the remaining characters).
      # %% 为求余符号
      sequence <-
        sequence[sequence != nth[i]]  # Remove the character we just used from the sequence.
    }
    
    nth[len] <-
      sequence  # There is only one character left in the sequence, which is the last one.
    return (nth)  # Return the sequence.
  }
}

# Print out the results.
cat("The result is:", GetNthLexPermutation(numSeq, n), "\n")

  

一个有意思的生成全排列的code. sequence不停截断循环还是挺有趣的

posted @ 2020-04-14 21:08  Zoe-D  阅读(137)  评论(0)    收藏  举报