我希望编写一个 R 脚本,该脚本将生成集合编号的所有可能组合,其中它们的乘积总和低于特定总数。
例如,我有这两个向量,x
代表我想要为其生成组合的元素,y
代表求乘积和的元素。
x <- c(2,4,6) #elements to find combinations
y <- c(24,48,72) #elements to find product sum
这里我的主要限制是x
任意组合的总乘积和。必须小于或等于 1244。
期望结果示例
|--------------|--------------|--------------|---------------------|
| Total of 2 | Total of 4 | Total of 6 | Total Product Sum |
|--------------|--------------|--------------|---------------------|
| 1 | 1 | 1 | 144 |
|--------------|--------------|--------------|---------------------|
| 2 | 2 | 2 | 288 |
|--------------|--------------|--------------|---------------------|
| 3 | 3 | 3 | 432 |
|--------------|--------------|--------------|---------------------|
| 4 | 4 | 4 | 576 |
|--------------|--------------|--------------|---------------------|
| 5 | 5 | 5 | 720 |
|--------------|--------------|--------------|---------------------|
| ... | ... | ... | ... |
|--------------|--------------|--------------|---------------------|
R 中的示例代码
我尝试使用以下代码,但它只能线性工作,而不是生成小于或等于 1244 的所有可能组合。
n_trials <- 30
# data frame to store all possible combinations and their product sum
combo_data <- data.frame(total_of_2 = rep(0,n_trials)
, total_of_4 = rep(0,n_trials)
, total_of_6 = rep(0,n_trials)
, total_product_sum = rep(0,n_trials))
for (i in 1:n_trials) {
# check that combination is at most 1244 sqft
if (i*24 + i*48 + i*72 <= 1244) {
# track number of each element in x
combo_data$total_of_2[i] <- i
combo_data$total_of_4[i] <- i
combo_data$total_of_6[i] <- i
# add total product sum
combo_data$total_product_sum[i] <- i*24 + i*48 + i*72
}
}
view(combo_data)
最佳答案
1244 以下的有效组合数量会随着 n
的增加而增加,所以我不太清楚这里的目标。也就是说,这是一个使用基础 R 的版本:
y <- c(24,48,72) #elements to find product sum
n <- 30
instances <- expand.grid(1:n, 1:n, 1:n)
instances$product_sum = rowSums(data.frame(Map('*', instances, y)))
instances <- subset(instances, product_sum <= 1244 )
结果的前几行:
Var1 Var2 Var3 product_sum
1 1 1 1 144
2 2 1 1 168
3 3 1 1 192
4 4 1 1 216
5 5 1 1 240
6 6 1 1 264
如果您仅使用原始 x
值 2、4 和 6,而不是 1:n
,则应该获得 27 个有效组合。
关于r - 获取给定乘积总和内的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62498691/