1

I wish to write a function that accepts two variables n and k, where n>k, and returns vectors composed out of the integer k. The function should return all possible vectors, where k is the largest number in the vector, and all of the elements in the vector sum to n. In short, what I want to accomplish is the following:

n = 10, k = 3 thus the vectors are as follow

(3,1,1,1,1,1,1,1)
(3,2,1,1,1,1,1)
(3,2,2,1,1,1)
(3,2,2,2,1)
(3,3,1,1,1,1)
(3,3,2,1,1)
(3,3,2,2)
(3,3,3,1)
Roland
  • 127,288
  • 10
  • 191
  • 288
Bernard
  • 67
  • 6
  • 1
    Hey and welcome to SO. Can you provide some of the things you've tried already? You can also take a look at [this](https://stackoverflow.com/q/30858688/7856717) similar post for insights on how to find all possible combinations to a given sum. – Steve Aug 21 '19 at 07:50
  • Also please note that we reserve `Rstudio` tag for issues on the specific IDE – Sotos Aug 21 '19 at 08:00

1 Answers1

2

You can use package RcppAlgos for this:

library(RcppAlgos)
n <- 10
k <- 3

#loop over 1:n
res <- lapply(seq_len(n), function(i) {
  #generate all combinations of a vector with constraint
  x <- comboGeneral(k, i, TRUE, constraintFun = "sum", 
             comparisonFun = "==", 
             limitConstraints = n)
  #remove solutions that don't contain k
  x[as.logical(rowSums(x == k)),]

  })

res <- res[lengths(res) > 0]

res <- lapply(res, function(x) if (is.matrix(x)) asplit(x, 1) else x)

library(rlist)
list.flatten(res)
#[[1]]
#[1] 1 3 3 3
#
#[[2]]
#[1] 2 2 3 3
#
#[[3]]
#...
Roland
  • 127,288
  • 10
  • 191
  • 288
  • Is their a way to split the matrices in the output list into vectors, then the list only contains vectors and not both? – Bernard Aug 21 '19 at 11:48
  • See the edit ... – Roland Aug 21 '19 at 11:58
  • I ran your code and saw that you have an error in your edited code; asplit => split. I changed the code and run it but my results differ from yours? $`1` [1] 1 2 3 2 3 3 3 3 $`1` [1] 1 1 1 2 2 2 3 2 3 3 $`1` [1] 1 1 1 1 1 1 1 2 3 2 3 3 [[4]] [1] 1 1 1 1 1 2 3 [[5]] [1] 1 1 1 1 1 1 1 3 > – Bernard Aug 21 '19 at 13:22
  • No, that is not an error: [`asplit`](https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/asplit) was added in R 3.6.0. You should update R. – Roland Aug 21 '19 at 13:30
  • Now it works, thank you for your assistance, I appreciate it. – Bernard Aug 21 '19 at 14:14
  • Feel free to click the check-mark next to the answer. – Roland Aug 21 '19 at 14:15