简体   繁体   中英

Find the combinations that add up to a number, followed by the next number until 0 - in R

I am trying to create a matrix of all the combinations that add up to a number followed by the combinations that add up to the next number until 0. For example

Input: N = 3
Output:
[1,]3 0
[2,]2 1
[3,]1 1 1
[4,]2 0
[5,]1 1
[6,]1 0
[7,]0

My question is, is there a package in R that can do this? or do I have to write my own function?

I would really appreciate any help or guidance on this. Thank you.

I think I have figured out the solution using the library partitions .

library(partitions)
n=7
df = t(as.matrix(blockparts(rep(n,n),n, include.fewer = FALSE))) # create a transposed matrix with the possible combinations
indx <- !duplicated(t(apply(df, 1, sort))) # find non - duplicates in sorted rows
df[indx, ] # select only the non - duplicates according to that index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM