代码之家  ›  专栏  ›  技术社区  ›  Ray Ban

从文本文件读取加权图

  •  0
  • Ray Ban  · 技术社区  · 7 年前

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

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

    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);
        }
    

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   luizfzs    7 年前

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

    // 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<>();
    

    理想情况下,您应该始终声明变量 外部 HashMap 这里使用的是覆盖您的输入不总是分组的情况,并且您避免每次都必须执行列表搜索。

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

    一次读取文件上的所有行。或者,根据问题的要求,您可以使用 Scanner 喜欢开 this anwer 但是,你必须改变在这些行上迭代的方式。

    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);
    }
    

    检查当前节点是否已在 哈希图 n 。否则,它将创建一个 Node 使用当前id并将其添加到 .

    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);
    }
    

    splittedLine 从索引1开始。 对于每个边缘数据,我们根据“,”(来自您的输入文件)进行分割,而 splittedEdge[0] 将是目标id和 splittedEdge[1] 将是到达目的地的成本。我们创建了一个 Edge 节点