2017-03-14 21 views
0

我有四個變量,我想以特定方式分配權重。如果我確定了每個重量的間隔,我應該使用哪個程序列出所有可能的解決方案?基本上我會有兩個約束 - 權重的總和應該是100,權重應該來自預定義的時間間隔。列出組合

我試圖解決的確切例子是:提前

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

謝謝!任何意見或建議是非常歡迎

+0

顯示一些數據使用'dput()'左右。幷包括您的預期輸出。 – Jimbou

+0

如果您決定使用python,請查看它們的迭代器功能。這使您可以生成所有組合,而無需將其顯式存儲在內存中。 – Roelant

+1

歡迎來到SO!請閱讀[問]和[mcve] ...然後編輯您的問題http://stackoverflow.com/posts/42781319/edit – jogo

回答

2

可以(針對這方面的問題)這樣做比較容易,R中使用expand.grid()蠻力所有組合。請注意,如果權重的間隔變大很多,則此解決方案不適合,因爲組合的數量太多。

# 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 
+0

非常感謝!你的回答對我很有幫助,因爲我不熟悉編程! –

2

您可以使用expand.grid更多,即

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 
+0

非常感謝!你的回答對我很有幫助,因爲我不熟悉編程! –