gpt4 book ai didi

r - 从向量中找出所有可能的数字组合以达到给定的总和(无重复)

转载 作者:行者123 更新时间:2023-12-01 07:09:13 27 4
gpt4 key购买 nike

我有一个向量“数字”,我想找出总和在 90 到 110 范围内的 1,2 或 3 个数字的所有可能组合。

我知道有很多帖子提供了解决问题的方法,但没有一个能满足我的需求。
至少在 R# 中不是

numbers <- c(40,60,20,65,45,30,5,70,100,85,75,10);
names(numbers) <- c("A","B","C","D","E","F","G","H","I","J","K","L")

结果应如下所示:
A + B
A + D
A + H
I
B + E
B + F
C + H
C + J
C + K
D + E
D + F
F + H
F + K
J + L

最佳答案

我编写了一个名为 RcppAlgos 的包这是为这些任务而构建的。有一个功能comboGeneral能够找到特定约束下的所有组合。观察:

comboBetween <- function(v, m, constraint) {
do.call(c, lapply(1:m, function(x) {
nums <- comboGeneral(v, x, constraintFun = "sum",
comparisonFun = c(">=", "<="),
limitConstraints = constraint)
apply(matrix(myNames[match(nums, numbers)],
ncol = x), 1, paste, collapse = " + ")
}))
}

下面是一个例子:
numbers <- c(40,60,20,65,45,30,5,70,100,85,75,10);
myNames <- c("A","B","C","D","E","F","G","H","I","J","K","L")

comboBetween(numbers, 4, c(90, 110))
[1] "I" "G + J" "G + I" "L + J" "L + I" "C + H"
[7] "C + K" "C + J" "F + B" "F + D" "F + H" "F + K"
[13] "A + B" "A + D" "A + H" "E + B" "E + D" "G + L + K"
[19] "G + L + J" "G + C + D" "G + C + H" "G + C + K" "G + C + J" "G + F + B"
[25] "G + F + D" "G + F + H" "G + F + K" "G + A + E" "G + A + B" "G + A + D"
[31] "G + E + B" "L + C + B" "L + C + D" "L + C + H" "L + C + K" "L + F + B"
[37] "L + F + D" "L + F + H" "L + A + E" "L + A + B" "C + F + A" "C + F + E"
[43] "C + F + B" "C + A + E" "G + L + C + B" "G + L + C + D" "G + L + C + H" "G + L + C + K"
[49] "G + L + F + E" "G + L + F + B" "G + L + F + D" "G + L + A + E" "G + C + F + A" "G + C + F + E"
[55] "G + C + A + E" "L + C + F + A" "L + C + F + E"

它非常有效,就像它写在 C++ 中一样以获得最佳性能。

关于r - 从向量中找出所有可能的数字组合以达到给定的总和(无重复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55817258/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com