更新时间:2023-11-22 23:42:04
pos <- structure(c(4L, 1L, 4L, 2L, 1L, 3L, 4L, 2L, 1L, 3L, 2L, 4L, 1L,
3L, 2L, 4L, 3L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 6L, 6L, 5L, 6L, 5L,
6L, 4L, 5L, 4L, 5L, 4L, 3L, 3L, 4L, 3L, 2L, 3L, 2L, 2L, 2L, 1L,
1L, 1L, 1L), .Dim = c(24L, 2L), .Dimnames = list(NULL, c("row", "col")))
ch <- c(5,7,10,5)
C <- 150
s <- c(1,1,1,1)
for (i in 24:1) {
# for(j in 1:4)
# {
# if (pos[i,1]==j) s[j] <- s[j]+1
# }
j <- pos[i,1]; s[j] <- s[j]+1
cost <- sum(ch*s)
if (cost>=C) break
}
s; cost
作为变体,可以遍历矩阵的第一列 pos
As a variant one can run through the first column of the matrix pos
for (j in pos[24:1, "row"]) {
s[j] <- s[j]+1
cost <- sum(ch*s)
if (cost>=C) break
}
s; cost