2017-05-05 39 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