下面是使用combn
一個基礎R方法。比方說你有整數1到12,你想找到所有的組5個號碼那筆以20
myGroups <- combn(1:12, 5)
mysums <- combn(1:12, 5, FUN=sum, simplify=TRUE)
myAnswers <- myGroups[, mysums == 20]
這將返回一個矩陣,其中列是數字的組:
myAnswers
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 1 1 1 1 1 2
[2,] 2 2 2 2 2 3 3
[3,] 3 3 3 4 4 4 4
[4,] 4 5 6 5 6 5 5
[5,] 10 9 8 8 7 7 6
這將很容易包裝在一個函數中。在下面的函數中,x是輸入向量,我在上面的例子中設置爲1:12,k和n在OP的問題中定義。
myfunction <- function(x, k, n) {
myGroups <- combn(x, k)
mysums <- combn(x, k, FUN=sum, simplify=TRUE)
myGroups[, mysums == n]
}
注
這種方法假定在X中的每個條目將被一次在計算上的整數使用,所以0:即最多使用它們的4,myfunction
返回添加到9 9:
myfunction(0:9, 4, 9)
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 1 1 2
[3,] 2 3 3
[4,] 6 5 4
注
如果目標是允許重複使用這些整數的,我們只是必須調整我們喂myfunction
。請注意,這將導致重複輸出集合,因爲訂單對combn
重要。
如果重複整數將參與,利用combn
已被修改爲返回一個列表,所以我們可以用unique
下降重複集:
myfunctionDupes <- function(x, k, n) {
# return list instead of matrix, with elements sorted
myGroups <- lapply(combn(x, k, simplify=FALSE), sort)
# find duplicates
dupes <- duplicated(myGroups)
# subset summations to those where myGroups is not a duplicate
mysums <- combn(x, k, FUN=sum, simplify=TRUE)[!dupes]
# subset myGroups to the unique values then those with sums == n
myGroups <- (myGroups[!dupes])[mysums == n]
# return a matrix
do.call(cbind, myGroups)
}
這需要一點時間來運行在@喬希 - 奧布萊恩的例子,但是它產生相同的結果:
myfunctionDupes(rep(0:9, 4), 4, 9)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16] [,17] [,18]
[1,] 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 2
[2,] 1 1 1 1 0 2 2 0 0 3 0 0 2 2 1 1 1 2
[3,] 2 3 4 1 1 3 2 2 3 3 4 0 3 2 2 3 1 2
[4,] 6 5 4 7 8 4 5 7 6 3 5 9 3 4 5 4 6 3
感謝,喬希,但我得到了落實時的restrictedparts誤差(4,3,include.zero = F),感謝 – weikangduan
@weikangduan很好的接收。這是由於'restrictedparts()'中的一個錯誤。查看我的編輯以獲得簡單的解決方法。 –
嗨@Josh,謝謝。但是我期待的結果是1 1 2,1 2 1和2 2 1.是否有解決這個問題的方法?謝謝。 – weikangduan