【问题标题】:Reading data points from a data file从数据文件中读取数据点
【发布时间】:2017-03-03 20:41:59
【问题描述】:

我有一个包含 1000 个数据点的数据文件,其组织方式如下:

1000
16   11
221   25
234   112
348   102
451   456

我正在尝试将文件读入我的程序并找到导致最短点到点总距离的点的排列。由于我对列表的经验很少,因此即使读取数据点也遇到了很多麻烦。有没有更好的方法来解决这个问题?如何通过最近邻算法运行列表?

public static void main(String[] args) throws IOException {
    File file = new File("output.txt");
    Scanner scanner = new Scanner(file);

    ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>();

    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        String[] fields = line.split("   ");

        arrayList.add(new shortestRoute(Integer.parseInt(fields[0]), Integer.parseInt(fields[1])));
    }
    scanner.close();

    System.out.println(arrayList);
}

我知道求点到点距离的公式是 SquareRoot[(x2-x1)^2-(y2-y1)^2]。我遇到的麻烦是将数据点输入贪心算法。

【问题讨论】:

  • 更安全地使用 .split("\\s+") 将跳过任意数量的空白字符
  • 到目前为止,您对排序进行了哪些尝试?我认为读取数据的方式没有太大问题。您可能需要在 arrayList.add 函数中进行空检查。
  • 如何计算点到点距离?只是mod(a-b)吗?
  • 使用 BufferedReader 可能性能更高,读取数据也比使用 Scanner 简单。
  • 试试scanner.nextInt()

标签: java algorithm file-io nearest-neighbor


【解决方案1】:

您正在使用四个空格分割输入字符串。查看输入文件,我假设这些数字也可以用制表符分隔。而不是使用四个空格,您应该寻找任何空白。拆分函数应该像这样改变:

String[] fields = line.split("\\s+");

【讨论】:

  • 您的想法是正确的,但鉴于nextLine 确保行尾被消耗,您不会在扫描仪未正确推进时遇到奇怪的nextFoo 错误。跨度>
  • 感谢您的意见。编辑了我的回复
【解决方案2】:

我认为是因为第一行是文件中的点数。

既然都是数字,那就坚持使用 Scanner。

public static void main(String[] args) throws IOException {
    File file = new File("output.txt");
    Scanner scanner = new Scanner(file);

    ArrayList<shortestRoute> arrayList = new ArrayList<shortestRoute>();

    for(int i =0, n = scanner.nextInt(); i < n; i++) {
        arrayList.add(new shortestRoute(scanner.nextInt(), scanner.nextInt()));
    }
    scanner.close();

    System.out.println(arrayList);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2014-03-16
    • 2013-09-20
    • 2018-07-06
    • 2014-01-07
    相关资源
    最近更新 更多