Sample with a max

前端 未结 5 1190
日久生厌
日久生厌 2021-01-19 01:57

If I want to sample numbers to create a vector I do:

set.seed(123)
x <- sample(1:100,200, replace = TRUE)
sum(x)
# [1] 10228

What if I

5条回答
  •  臣服心动
    2021-01-19 02:36

    I thought of stars and bars and partitions in combinatorics:

    foo <- function(n,total) {
      while(!exists("x",inherits=FALSE) || 1 %in% diff(x)) {
        x <- sort(c(0,sample.int(n+total,n-1,replace=FALSE),n+total))
      }
      print(x)
      sort(diff(x)-1)
    }
    

    Another method is to use the partitions package. This is more suited to enumerating all partitions, but it is okay for now. It works as long as your total number is small.

    require(partitions)
    foo <- function(n,total) { 
      x <- restrictedparts(total,n,include.zero=FALSE)
      return(x[,sample.int(ncol(x),1)])
    }
    

提交回复
热议问题