【发布时间】:2018-07-24 02:58:03
【问题描述】:
我正在做一个项目,我达到了这一点,但实际上我从一周前开始就一直坚持下去,我尝试了很多想法,但所有为我的算法编写代码的尝试都失败了。
边的顺序是:1--3、1--4、3--2
对于每条边,在每个顶点上定义一个随机游走以移动到它的一个邻居,例如:
对于第一条边,v1=1 ,v2=3, n1=3,4 和 n2=1,2 按顺序排列,因此从 v1 和 v2 开始的可能移动是:
1 to 3,3 to 1
1 to 4,3 to 1
1 to 3,3 to 2
1 to 4,3 to 2
对于第二条边,依次为v1=1 ,v2=4, n1=3,4 和n2=1,因此从v1 和v2 可能的移动是:
1 to 3,4 to 1
1 to 4,3 to 1
对于第三条边,依次为v1=3 ,v2=2, n1=1,2和n2=3,所以从v1和v2可能的移动是:
3 to 1,2 to 3
3 to 2,2 to 3
对于整个图表,只有 8 个可能的移动,所以我有 8 个变量来构造约束矩阵
让我们用 x 来表示移动(根据它们出现的顺序);即
(1 to 3,3 to 1) to be represented by x_1
(1 to 4,3 to 1) to be represented by x_2
:
(3 to 1,2 to 3) to be represented by x_7
(3 to 2,2 to 3) to be represented by x_8
我想根据这些移动构建所需的约束矩阵,约束的数量将等于\sum{i} ( number of neighbors for v1(i) * number of neighbors for v2(i) ),在我们的图中为 10。
我构建这个矩阵的算法是:
Step1: 1) select 1st edge, fix v1, v2, n2
2) change n1 and fill the 1st row of the matrix by 1's in the place of the resulted moves and 0 if there is no similar move on the graph until you finish all elements in n1.
Step2: move to the 2nd row of the matrix and select the 2nd element of n2 and
1) loop over n1
2) fill the 2nd row by 1's in the place of the resulted moves until you finish all elements in n1.
Step3: since you selected all elements in n1 and n2 for the vertices in the first edge move to a new row in the matrix
Step4: Select next edges and do the same work done before until you finish all edges.
Step5: select the 1st edge again and do the same work but while fixing v1,v2 &n1, loop over n2
根据该算法得到的矩阵将是:
1 1 0 0 0 0 0 0
0 0 1 1 0 0 0 0
0 0 0 0 1 1 0 0
0 0 0 0 0 0 1 1
1 0 1 0 0 0 0 0
0 1 0 1 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1
我没有做的是:如何让矩阵知道有移动并在它的位置用1替换它,如果没有移动它用0替换它位置
我的代码是:
library(igraph)
graph<-matrix(c(1,3,1,4,3,2),ncol=2,byrow=TRUE)
g<-graph.data.frame(d = graph, directed = FALSE)
countercol<-0
for (edge in 1:length(E(g))){
v1<-ends(graph = g, es = edge)[1]
v2<-ends(graph = g, es = edge)[2]
n1<-neighbors(g,v1,mode=c("all"))
n2<-neighbors(g,v2,mode=c("all"))
countercol=countercol+(length(n1)*length(n2))
}
counterrow<-0
for (edge in 1:length(E(g))){
v1<-ends(graph = g, es = edge)[1]
v2<-ends(graph = g, es = edge)[2]
n1<-neighbors(g,v1,mode=c("all"))
n2<-neighbors(g,v2,mode=c("all"))
counterrow=counterrow+(length(n1)+length(n2))
}
for (edge in 1:length(E(df))){
v1<-ends(graph = df, es = edge)[1]
v2<-ends(graph = df, es = edge)[2]
n1<-neighbors(df,v1,mode=c("all"))
n2<-neighbors(df,v2,mode=c("all"))
...
...
...
}
我不是在找人来编写代码,我想要的是让程序区分可能的移动并将 1 和 0 存储在结果移动的合适位置。
非常感谢您的任何帮助
【问题讨论】:
-
我很困惑你所说的
v1=1 ,v2=3, n1=3,4和n2=1,2是什么意思。v表示顶点,是吗?n代表什么? -
您如何在这些示例中定义
n2?我不明白你对问题的描述。 -
@InfiniteFlashChess 邻居
-
@InfiniteFlashChess v1, v2 是第一个和第二个顶点,因此 n1, n2 是 v1 和 v2 的邻居(相邻和连接的顶点)
-
@MrFlick n2 是 v2 的邻居(连接和相邻的顶点),v2 是任何边中的第二个顶点。函数neighbors(g,edge)在指定顶点时确定这些邻居
标签: r algorithm matrix optimization igraph