2017-05-05 37 views
0

我使用r和 欲填充整數形式1中的8 lenght維向量/表4相對於以下條件:填充與intgers矢量相對於約束

vector [i]<= vector[i+1] 

所有integrs應該存在

例如:

1 1 1 1 2 2 3 4 may be a solution 

1 2 1 1 2 3 3 4 isn't a solution to my problem 

我也想知道是否有一種方法可以列出所有的解決方案

+1

您到目前爲止嘗試了什麼?你有什麼想法嗎? – ventiseis

+0

如果向量中的所有數字在1到4之間,'sort(vector)'將保證結果是一個解決方案。 – www

回答

0

要獲得所有解決方案,請爲號碼1:4預留4個插槽(因爲每個號碼必須至少出現一次),並考慮所有可能的長度 - 4個序列1:4以填充剩餘的插槽。排序和刪除重複項留下35個非遞減序列:

# The sequences will be the rows of a matrix. First, the 'reserved' slots: 
reserved = matrix(1:4, 256, 4, byrow=TRUE) 
# Add all combinations of 1:4 to fill the remaining four slots: 
result = cbind(reserved, 
       unname(as.matrix(expand.grid(1:4, 1:4, 1:4, 1:4)))) 

# Now simply sort and de-duplicate along rows: 
result = t(apply(result, 1, sort)) 
result = unique(result) 

> head(result) 
#  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] 
# [1,] 1 1 1 1 1 2 3 4 
# [2,] 1 1 1 1 2 2 3 4 
# [3,] 1 1 1 1 2 3 3 4 
# [4,] 1 1 1 1 2 3 4 4 
# [5,] 1 1 1 1 2 2 3 4 
# [6,] 1 1 1 2 2 2 3 4