java - 如何创建点文件
问题描述
我有一个生成随机图 (DAG) 的程序,如何提取输出图并转换为文件点格式以便在 GraphViz 中可视化它?或者还有其他方法可以做到吗?这是代码(我省略了所有依赖项)和一个简单的生成输出
public class DigraphGenerator {
private static final class Edge implements Comparable<Edge> {
private final int v;
private final int w;
private Edge(int v, int w) {
this.v = v;
this.w = w;
}
public int compareTo(Edge that) {
if (this.v < that.v) return -1;
if (this.v > that.v) return +1;
if (this.w < that.w) return -1;
if (this.w > that.w) return +1;
return 0;
}
}
private DigraphGenerator() { }
public static Digraph dag(int V, int E) {
if (E > (long) V*(V-1) / 2) throw new IllegalArgumentException("Too many edges");
if (E < 0) throw new IllegalArgumentException("Too few edges");
Digraph G = new Digraph(V);
SET<Edge> set = new SET<Edge>();
int[] vertices = new int[V];
for (int i = 0; i < V; i++)
vertices[i] = i;
StdRandom.shuffle(vertices);
while (G.E() < E) {
int v = StdRandom.uniform(V);
int w = StdRandom.uniform(V);
Edge e = new Edge(v, w);
if ((v < w) && !set.contains(e)) {
set.add(e);
G.addEdge(vertices[v], vertices[w]);
}
}
return G;
}
public static void main(String[] args) {
int V = Integer.parseInt(args[0]);
int E = Integer.parseInt(args[1]);
StdOut.println("DAG");
StdOut.println(dag(V, E));
StdOut.println();
}
}
输出示例:
DAG 12 个顶点,10 个边 0:2 1 1:2:3:4:8 5:9 6:7:8 4 8:9:8 10:5 11:5 6
DAG 12 个顶点,10 个边 0:8 1:8 2:5 3:4:5 5:6:7 9 8 7:8:9:10:11:5 7 3
解决方案
像这样的东西应该工作:
void writeDot(Digraph d){
try(BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("g.dot")))){
out.write("digraph {");
out.newLine();
for(Edge e:d.getEdges()){
out.write(e.v+" -> "+e.w);
out.newLine();
}
out.write("}");
}
}
或者您可以查看https://github.com/nidi3/graphviz-java,它负责生成点文件并调用 graphviz 并直接生成 png 图像。
推荐阅读
- javascript - 使用类似于 onSelect() 的 onChange() 将选择值打印到控制台
- laravel - Laravel 7 - 电子邮件验证但没有“验证您的电子邮件地址”页面
- javascript - 如何使用 mongoose 和 node.js 将 mongodb 时间戳转换为 dd-mm-yyyy 格式?
- r - 如何在 R 中使用 grid.show.viewport() 函数?
- javascript - 使用 firebase auth 注册用户会引发错误,但仍能正确注册
- python - Pandas groupby 计数和填充无计数为 0
- mysql - 插入新元素时如何向下推 ID
- apache-kafka - Kafka docker 撰写外部连接
- android - 如何更快地从 Firebase 中检索数据
- javascript - Pause functions on page history forward backward