R 从向量生成具有给定列数的特殊矩阵(列和的最大值最小)

R 从向量生成具有给定列数的特殊矩阵(列和的最大值最小),r,math,optimization,statistics,combinations,R,Math,Optimization,Statistics,Combinations,最近我遇到了这样一个问题:给定一个向量,需要生成一个具有给定列数的特殊矩阵。需要指出的是,如果向量中的元素不足以填充生成的矩阵,则将0放入生成矩阵的最后一行。对于生成的矩阵,它要求列和的最大值为最小值 以下是给定问题的代码: x <- c(10, 10, 9, 21, 8, 3, 7, 23, 1, 5, 26) x ncol <- 4 x <- sort(x, decreasing = TRUE) x nx <- length(x) nrow <- ceili

最近我遇到了这样一个问题:给定一个向量,需要生成一个具有给定列数的特殊矩阵。需要指出的是,如果向量中的元素不足以填充生成的矩阵,则将0放入生成矩阵的最后一行。对于生成的矩阵,它要求列和的最大值为最小值

以下是给定问题的代码:

x <- c(10, 10, 9, 21, 8, 3, 7, 23, 1, 5, 26)
x
ncol <- 4

x <- sort(x, decreasing = TRUE)
x

nx <- length(x)
nrow <- ceiling(nx / ncol)

# add 0 in the end
if (nx < nrow * ncol) {
  x <- c(x, rep(0, length.out = nrow * ncol - nx))
}
x

x这里有一种可能的贪婪启发式方法,可能仅适用于
x
中的所有值均为非负值的情况

首先从最大值开始。使用最大值初始化第一行。然后,将每个后续非零值添加到具有最小和的列中

x <- c(10, 10, 9, 21, 8, 3, 7, 23, 1, 5, 26)
x <- sort(x, decreasing=TRUE)
nc <- 4L
nr <- ceiling(length(x) / 4)

#Initialize the first row with the largest values
y <- c(x[seq_len(nc)], rep(0, nc*nr-4L))
#use list to store each row of the final matrix
yl <- split(y, (seq_along(y)-1L) %% nc)

#for subsequent values
for (k in (nc+1L):length(x)) {
    #find the smallest sum among the rows provided the rows are not totally filled
    idx <- names(which.min(lapply(yl[sapply(yl, function(x) any(x==0))], sum)))

    #store this value the appropriate row
    yl[[idx]][min(which(yl[[idx]]==0L))] <- x[k]
}

#output desired matrix
matrix(unlist(yl), ncol=nc)

对不起,我没听懂。首先你说代码是针对给定问题的,但后来你说它无法找出如何获得给定问题的解决方案(代码?)。是哪一个?你到底有什么问题?(通常需要帮助的问题应该包括预期输出和实际输出。)@JaMiT我编辑了这个问题,其中
mat_a
是预期输出,但
mat_b
是我得到的,但它是错误的~哦,我明白了。您将输出与代码合并。当你浏览代码寻找问题时,很容易漏掉。@JaMiT谢谢。编辑后会更清晰,谢谢。它起作用了。事实上,向量
x
中没有负值。
# generate mat_b
mat_b <- rbind(c(26, 23, 21, 10),
               c(7, 8, 9, 10),
               c(0, 1, 3, 5))
mat_b
max(colSums(mat_b)) # 33
x <- c(10, 10, 9, 21, 8, 3, 7, 23, 1, 5, 26)
x <- sort(x, decreasing=TRUE)
nc <- 4L
nr <- ceiling(length(x) / 4)

#Initialize the first row with the largest values
y <- c(x[seq_len(nc)], rep(0, nc*nr-4L))
#use list to store each row of the final matrix
yl <- split(y, (seq_along(y)-1L) %% nc)

#for subsequent values
for (k in (nc+1L):length(x)) {
    #find the smallest sum among the rows provided the rows are not totally filled
    idx <- names(which.min(lapply(yl[sapply(yl, function(x) any(x==0))], sum)))

    #store this value the appropriate row
    yl[[idx]][min(which(yl[[idx]]==0L))] <- x[k]
}

#output desired matrix
matrix(unlist(yl), ncol=nc)
     [,1] [,2] [,3] [,4]
[1,]   26   23   21   10
[2,]    5    7    8   10
[3,]    0    1    3    9