【发布时间】: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