使用特定条件对行进行采样

时间:2017-12-11 17:14:19

标签: permutation sample

我正在尝试为我和我的室友制定某种时间表,但我不知道该怎么做,我甚至不确定它是否可行。

我想要做的简化版本是:让我们假设我们有5个人(John,Mike,Jack,Collin和Anna)和3个家务(1,2,3)。我想在个人中传播这些家务,同时满足几个标准。例如,每个人每月必须做两次家务活#1。

我真的在黑暗中拍摄,我不知道如何处理这个问题。到目前为止,我已经使用排列来找到杂务之间的所有可能组合,然后我将标准应用于几个循环。这是代码:

####################
#install.packages("gtools")
library(gtools)
maat=permutations(3, 4, repeats.allowed = T)#Finding all the possible combinations of the chores for 4 weeks and 3 chores.
#The following loop applies two criteria: #
#1) in a 4-week period (1 month) chore #1 must be done two times
#2) in a 4-week period all of the chores must be done at least one
o=k=0
for (i in 1:nrow(maat)) {
  if ((sum(maat[i,] %in% 1) == 2) &&  all(1:3 %in% maat[i,])) {
    o[k]=i
    k = k + 1}
}
newmaat<-maat[o,] #the filtered matrix

cleaningRot<-matrix(ncol=4, nrow=5
      , data=newmaat[sample(nrow(newmaat), size=5, replace=F),]
      ,  dimnames = list(c("John", "Mike", "Jack", "Collin", "Anna")
      , c(paste0("Week",1:4)))) # This is the schedule for each individual
##The following loop applies 2 more criteria:
#1) all three chores must be done per week
#2) each week chores #1 and #2 must be done twice
while(!all(1:3 %in% cleaningRot[,1])| #All three chores must be in the 1st week
      !all(1:3 %in% cleaningRot[,2])| #All three chores must be in the 2st week
      !all(1:3 %in% cleaningRot[,3])| #All three chores must be in the 3st week
      !all(1:3 %in% cleaningRot[,4])  #All three chores must be in the 4st week
      |
      !(sum(cleaningRot[,1] %in% 1) == 2) && !(sum(cleaningRot[,1] %in% 2) == 2)| #Chores #1 and #2 must be done 2 times in week 1
      !(sum(cleaningRot[,2] %in% 1) == 2) && !(sum(cleaningRot[,2] %in% 2) == 2)|#Chores #1 and #2 must be done 2 times in week 2
      !(sum(cleaningRot[,3] %in% 1) == 2) && !(sum(cleaningRot[,3] %in% 2) == 2)|#Chores #1 and #2 must be done 2 times in week 3
      !(sum(cleaningRot[,4] %in% 1) == 2) && !(sum(cleaningRot[,4] %in% 2) == 2)#Chores #1 and #2 must be done 2 times in week 4

  ){
  cleaningRot<-matrix(ncol=4, nrow=5, data=newmaat[sample(nrow(newmaat), size=5, replace=F),],
                      dimnames = list(c("John", "Mike", "Jack", "Collin", "Anna"), c(paste0("Week", 1:4))))
}


 ######################################

所以,基本上,我在排列之间进行抽样,直到结果满足给定的假设;一种高度随机的方法,但我的编程知识不允许我做更多。

这种方法的另一个问题是,如果家务/个人/周的数量更大,则根据假设随机找到合适的时间表几乎是不可能的。

所以我的问题是,如果你知道一种更有条理的方法,而不是从一组数字中随机抽样?

感谢您为我的杂乱代码道歉。

0 个答案:

没有答案