使用关于约束的intgers填充向量

时间:2017-05-05 15:42:15

标签: r algorithm

我使用r和 我想填充一个8长度的维度向量/表,其整数形式为1到4,相对于下面的条件:

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

所有积分都应该存在

示例:

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 个答案:

答案 0 :(得分:0)

要获得所有解决方案,请为数字1:4保留四个插槽(因为每个数字必须至少出现一次),并考虑1:4的所有可能的长度为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