簡體   English   中英

找到加起來等於一個數字的組合,然后是下一個數字,直到 0 - 在 R 中

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

我正在嘗試創建一個矩陣,其中包含加起來為一個數字的所有組合,然后是加起來為下一個數字的組合,直到 0。例如

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

我的問題是,R中是否有一個package可以做到這一點? 還是我必須自己寫 function?

我真的很感激任何幫助或指導。 謝謝你。

我想我已經找到使用庫分區的解決方案。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM