0

Looking to return a list of all ways of choosing N non-negative integers so that they sum to M

For instance if N = 3 and M = 2 this would return

[[1]]
[1] 0 0 2

[[2]]
[1] 0 1 1

[[3]]
[1] 0 2 0

[[4]]
[1] 1 0 1

[[5]]
[1] 1 1 0

[[6]]
[1] 2 0 0
Elis
  • 70
  • 10
  • 1
    `partitions::compositions(2, 3)` – Henrik Aug 05 '22 at 15:09
  • 1
    Can you try `library(RcppAlgos);comboGeneral(seq_len(N), M, constraintFun = "sum", comparisonFun = "==", limitConstraints = N)` – akrun Aug 05 '22 at 15:14
  • @Henrik Thank you, but can't seem to get list output as desired (class = partition, which I'm not sure how to deal with) – Elis Aug 05 '22 at 15:23
  • 1
    @Elis `asplit` happily accepts the result: `x = compositions(2, 3)`; `asplit(x, 2)`. Or if you want perform an explicit coercion of the partition, first wrap the result in `as.matrix`. – Henrik Aug 05 '22 at 15:27
  • You actually do not want combinations based on your example, you want permutations. – socialscientist Aug 05 '22 at 15:49
  • The duplicated answer doesn't return a list. See here for a solution that returns a list and doesn't require a package dependency: https://stackoverflow.com/a/73252355/3614648 – socialscientist Aug 05 '22 at 15:52

0 Answers0