从数据文件中读取数据点
Reading data points from a data file
我有一个包含 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]。我遇到的问题是将数据点输入贪婪算法。
您正在使用四个 space 拆分输入字符串。查看输入文件,我假设数字也可以用制表符分隔。与其使用四个 space,不如寻找任何白色 space。拆分函数应该像这样改变:
String[] fields = line.split("\s+");
我认为是因为第一行是文件中的点数。
因为都是数字,所以坚持使用扫描仪。
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);
}
我有一个包含 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]。我遇到的问题是将数据点输入贪婪算法。
您正在使用四个 space 拆分输入字符串。查看输入文件,我假设数字也可以用制表符分隔。与其使用四个 space,不如寻找任何白色 space。拆分函数应该像这样改变:
String[] fields = line.split("\s+");
我认为是因为第一行是文件中的点数。
因为都是数字,所以坚持使用扫描仪。
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);
}