Milica Maricic
Milica Maricic

Reputation: 23

List out combinations

I have four variables who I want to assign weights in a specific way. If I have determined an interval for each weight, which program should I use to list out all the possible solutions? Basically I would have two constraints - the sum of weights should be 100 and the weights should come from the predefined interval.

The precise example I am trying to solve is:

25<= weight1<=31
21<= weight2<=26
17<= weight3<=24
25<= weight4<=31
weight1+weight2+weight3+weight4=100

Thanks in advance! Any comment or suggestion is more than welcome

Upvotes: 0

Views: 72

Answers (2)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 60000

You can do this relatively easily (for this particular problem), using expand.grid() in R to brute force all the combinations. Note, that if the interval of the weights gets a lot bigger this solution wouldn't be suitable because there would be too many combinations.

#  Make all the combinations of weights
all <- expand.grid( 25:31, 21:26, 17:24 , 25:31 )
#  Which add up to 100?
idx <- rowSums( all ) == 100

#  Subset the original matrix to only return those rows which add to 100
head( all[ idx , ] )
#    Var1 Var2 Var3 Var4
#84    31   26   18   25
#119   31   25   19   25
#125   30   26   19   25
#154   31   24   20   25
#160   30   25   20   25
#166   29   26   20   25

Upvotes: 2

Sotos
Sotos

Reputation: 51592

You can use expand.grid, i.e.

d1 <- expand.grid(25:31, 21:26, 17:24, 25:31)
d2 <- d1[rowSums(d1)==100,]

head(d2, 5)
#     Var1 Var2 Var3 Var4
#84     31   26   18   25
#119    31   25   19   25
#125    30   26   19   25
#154    31   24   20   25
#160    30   25   20   25

Upvotes: 2

Related Questions