![](/img/trans.png)
[英]How do i display a matrix array(that i created using 1s and 0s) on the html canvas with javascript?
[英]How to create a matrix of 0s and 1s such that rows and columns sum up to particular value?
我需要生成一个具有n
列和m
行的矩阵,其中每个单元格可以为0
或1
,这样每列中的数字之和等于c
,每行中的数字之和等于r
。 如果不可能(可能大部分时间),则列总和应为c+/-d
,行应为r+/-d
以使max(所有行和列的d)尽可能小。 换句话说,行的每个和应接近r
,列的每个和应接近c
。
为了说明当不存在完美解决方案时我在寻找什么,该解决方案:
1.1.1.......
1.1.1.......
...1..1...1.
...1.1..1...
....1...1..1
比这个解决方案更好:
1.1.1.......
1.1.1.......
...1..1...1.
...1.1..1...
....11..1...
因为最后一行与先前的解决方案的总和为0(与1比较),所以与所需的行总和为2的距离更远。
创建一个仅容纳行的矩阵很容易,可以对向量恰好为r
1s
进行排列。 但是如何满足第二个条件呢? 查找总和过高而又太低的列并交换一些数字? 这是否有帮助,需要多长时间,甚至无法终止,如果不可能获得理想的结果,我什么时候停止? 有没有更好的办法?
您可以使用伪代码或您选择的语言,也可以只使用随机内容。
我发现在给定行和列总和的情况下查找二进制矩阵是否存在,这涉及到回答是否可能,甚至构造一个可能的解决方案。 如果不可能的话,这种解决方案将具有很大的ds。
还有这篇论文https://www.sciencedirect.com/science/article/pii/S0012365X06003980我不是很了解,但它似乎也与构建完美的解决方案有关
这可以通过整数线性编程来完成。
library(lpSolve)
# inputs
nr <- 3 # no of rows
nc <- 3 # no of cols
r <- 2 # sum of each row equals r
c <- 2 # sum of each col equals c
obj <- rep(1, nr * nc)
const.mat <- rbind(
t(rep(1, nc) %x% diag(nr)), # this matrix multiplied by c(m) is row sums
(diag(nc) %x% t(rep(1, nr))) # this matrix multiplied by c(m) is col sums
)
const.rhs <- c(rep(r, nr), rep(c, nc))
out <- lp(obj = obj, const.mat = const.mat, const.dir = "=", const.rhs = const.rhs,
all.bin = TRUE)
out
## Success: the objective function is 6
matrix(out$solution, nr, nc)
## [,1] [,2] [,3]
## [1,] 0 1 1
## [2,] 1 0 1
## [3,] 1 1 0
您可以为此使用igraph
包中的sample_degseq函数,该igraph
将创建具有给定顶点度的图。 此图的邻接矩阵将具有您想要的属性。
library(igraph)
row_col_sum = 3
dim = 8
g = sample_degseq(rep(row_col_sum,dim), method = "simple.no.multiple")
as_adj(g)
输出:
8 x 8 sparse Matrix of class "dgCMatrix"
[1,] . . . . . 1 1 1
[2,] . . 1 1 1 . . .
[3,] . 1 . . 1 . 1 .
[4,] . 1 . . . 1 . 1
[5,] . 1 1 . . . 1 .
[6,] 1 . . 1 . . . 1
[7,] 1 . 1 . 1 . . .
[8,] 1 . . 1 . 1 . .
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.