【发布时间】:2014-12-12 00:32:43
【问题描述】:
我必须编写一个程序,总共生成 30 个图,其中 5 个有 10 个独特的边,5 个有 20 个独特的边,等等,最多 60 个。然后我必须在每个图表中取平均数量的组件5 个图表。但是,我的程序始终挂在同一位置。当它试图做第 16 条图和第 11 条边时,它总是失败。我忽略了连接组件静态方法,因为这与问题无关,我相信。请注意,这是早期优化副本的草稿,两者都挂在同一个地方。
首先,我用所需的 26 个顶点制作一个图,然后将相同的图放入数组中的 30 个点中的每一个中,然后将唯一的边放入每个图中。
edgeIs 方法和 indexIs 方法在我正在使用的图形 ADT 中。
代码如下:
import ch05.queues.LinkedUnbndQueue;
import ch05.queues.UnboundedQueueInterface;
import java.util.Random;
public class UniqueEdgeGraph2 {
public static void main (String[] args) {
final int numGraphs2 = 5;
int numEdges = 10;
double sum = 0;
int index = 0;
Random rand = new Random();
int randomNum1 = 0, randomNum2 = 0, flag = 0;
UnweightedGraph<Integer>[] graphArray = (UnweightedGraph<Integer>[]) new UnweightedGraph[30];
UnweightedGraph<Integer> graph;
for (int i = 0; i < 30; i++)
graphArray[i] = new UnweightedGraph<Integer>();
for (int i = 0; i < 30; i++)
for (int j = 0; j < 26; j++)
graphArray[i].addVertex(j);
for (int i = 0; i < 6; i++) { // it is done 6 times because 30 graphs are needed in total and numGraphs is 5
for (int j = 0; j < numGraphs2; j++) {
for (int k = 0; k < numEdges; k++) {
while (flag == 0) {
randomNum1 = rand.nextInt(26);
randomNum2 = rand.nextInt(26);
if (graphArray[index].edgeIs(randomNum1, randomNum2) == false) {
graphArray[index].addEdge(randomNum1, randomNum2);
flag = 1;
}
}
flag = 0;
}
sum += CountConnectedComponents(graphArray[index]);
index++;
}
System.out.println("Average # of Connected Components for five graphs with " + numEdges + " unique edges is: "
+ sum/5.0);
sum = 0;
numEdges += 10;
}
}
public boolean edgeIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns true
// otherwise, returns false.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
return (edges[row][column]);
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
【问题讨论】:
-
你能不能把.edgeIs函数也发上来?
-
你的意思是
hang还是endless loop -
我发布了 edgeIs 函数。我的意思是挂起,当我调试它时,它只是因为某种原因停在那里。我有一个较早的版本,对于具有相同数量的唯一边的 5 个图桶中的每一个,我都会有相同的重复循环,并且在停止之前它会在前 3 个循环中运行良好。
-
这个代码
return (edges[row][column]);是什么edges在哪里定义的?我想这总是返回 false,或者抛出一些你没有告诉我们的异常。 -
这段代码还能编译吗?
标签: java graph graph-theory