I am looking to write an R script that will generate all possible combinations of a collection numbers for which their product sum is under a certain total.
For example, I have these two vectors, x representing the elements I want to generate combinations for, y representing the elements to find the product sum.
x <- c(2,4,6) #elements to find combinations
y <- c(24,48,72) #elements to find product sum
My main constraint here is that the total product sum of any combination of x must be less than or equal to 1244.
Example of Desired Result
|--------------|--------------|--------------|---------------------|
| 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 |
|--------------|--------------|--------------|---------------------|
| ... | ... | ... | ... |
|--------------|--------------|--------------|---------------------|
Sample Code in R
I have tried using the following code, but it only works linearly instead of generating all possible combinations that are less than or equal to 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)