从文本文件中读取加权图

Read weighted graph from text file

我必须从文本文件创建加权图。下面是文本文件的外观示例。第一个数字是实际火车站的 ID。第二个数字是一个可能的目的地,逗号后面是以秒为单位的时间,它需要旅行。第三个数字是另一个可能的目的地。

060060101832 060063101842,78 060054104822,90
060054104822 060060101832,90 060057104812,90 060058101502,90 060054105611,66
060057104812 060054104822,90 060057102802,72 

我想将路由存储在 ArrayList 中。每个路由对象应如下所示:

Start: 060060101832 
Destination: 060063101842
Time: 78

问题是,我必须为同一起始位置存储多条路线。如何使用扫描仪正确读取行?我的方法是:

while (routes.hasNext()) {
        routes.useDelimiter(",| |\n");
        String start = routes.next();
        String dest= routes.next();
        String time= routes.next();
        Edge edge = new Edge(start, dest, time);
        edges.add(edge);
    }

由于我无法返回文本文件,所以我无法想象正确的解决方案应该是什么样子。

不是完整的代码也没有经过测试。它可能有效也可能无效,但无论如何它都会指导你。

// Java 8
Node n;
Edge e;
String[] splittedLine;
String[] splittedEdge;
HashMap<String, Node> stationNumberToNode = new HashMap<>();
// if the file is not too large, you can read the file at once
List<String> lines = Files.readAllLines(new File("path/to/file.txt").getPath());
for(String line : lines){
  splittedLine = line.split(" ");
  if((n = stationNumberToNode.get(splittedLine[0]) == null){
    n = new Node(splittedLine[0]); // assuming your Node has a constructor that takes the station id
    stationNumberToNode.put(stationNumberToNode[0], n);
  }
  for(int i = 1; i < splittedLine.lenght; ++i){
    splittedEdge = splittedLine[i].split(",");
    e = new Edge(splittedEdge[0], splittedEdge[1]); // assuming your Edgehas a constructor that takes the destination station and the cost
    n.addEdge(e);
  }
}

说明

Node n;
Edge e;
String[] splittedLine;
String[] splittedEdge;
HashMap<String, Node> stationNumberToNode = new HashMap<>();

理想情况下,您应该始终在外部 循环中声明变量,这样您就可以避免在每次迭代时都分配新内存。因此,我们在进入循环之前声明了 5 个变量。这里使用 HashMap 来涵盖您的输入并不总是分组的情况,并且您避免每次都必须执行列表搜索。

List<String> lines = Files.readAllLines(new File("path/to/file.txt").getPath());

一次读取文件中的所有行。或者,根据问题的要求,您可以像 this anwer 一样使用 Scanner 读取文件。不过,您必须更改迭代这些行的方式。

splittedLine = line.split(" ");

拆分“ ”上的行,因为您的输入文件格式正确。

if((n = stationNumberToNode.get(splittedLine[0]) == null){
  n = new Node(splittedLine[0]); // assuming your Node has a constructor that takes the station id
  stationNumberToNode.put(stationNumberToNode[0], n);
}

检查当前节点是否已经在HashMap上。如果是,它将存储在变量n中。否则,它将使用当前 ID 创建一个 Node 并将其添加到我们的 HashMap.

for(int i = 1; i < splittedLine.lenght; ++i){
  splittedEdge = splittedLine[i].split(",");
  e = new Edge(splittedEdge[0], splittedEdge[1]); // assuming your Edgehas a constructor that takes the destination station and the cost
  n.addEdge(e);
}

由于输入文件中的所有内容都是目的地站及其成本 (id,cost),我们从索引 1 开始迭代 splittedLine。 对于每个边缘数据,我们根据“,”(来自您的输入文件)进行拆分,而 splittedEdge[0] 将是目的地 ID,而 splittedEdge[1] 将是该目的地的成本。我们使用该信息创建一个 Edge,并将 Edge 添加到 Node 对象。