Код: Выделить всё
import java.util.Random;
public class Search {
static class Point {
static final int MAXIMUM = 100;
final int x;
final int y;
final int z;
Point(int x, int y, int z) {
this.x = verify(x);
this.y = verify(y);
this.z = verify(z);
}
Point(Random random) {
this(
random.nextInt(Point.MAXIMUM),
random.nextInt(Point.MAXIMUM),
random.nextInt(Point.MAXIMUM));
}
int getDistance(Point point) {
return Math.abs(x - point.x) + Math.abs(y - point.y) + Math.abs(z - point.z);
}
static int verify(int value) {
if ((0 > value) || (MAXIMUM < value)) {
throw new IllegalArgumentException();
}
return value;
}
}
static class Line {
final Point[] points;
Line(Point[] points) {
this.points = points;
}
Line(Random random, int indices) {
points = new Point[indices];
for (int j = 0; j < points.length; j++) {
points[j] = new Point(random);
}
}
int getDistance(Line line) {
if (points.length != line.points.length) {
throw new IllegalArgumentException();
}
int distance = 0;
for (int i = 0; i < points.length; i++) {
distance += points[i].getDistance(line.points[i]);
}
return distance;
}
}
static class DataSet {
final int indices;
final Line[] lines;
DataSet(Line[] lines) {
// TODO - Verify all lines have the same number of points
indices = lines[0].points.length;
this.lines = lines;
}
DataSet(Random random) {
indices = 1 + random.nextInt(99);
lines = new Line[1 + random.nextInt(999999)];
for (int i = 0; i < lines.length; i++) {
lines[i] = new Line(random, indices);
}
}
Line findClosest(Line line) {
int closestDistance = Integer.MAX_VALUE;
Line closestLine = null;
for (Line nextLine : lines) {
int distance = line.getDistance(nextLine);
if ((Integer.MAX_VALUE == closestDistance) || (distance < closestDistance)) {
closestDistance = distance;
closestLine = nextLine;
}
}
return closestLine;
}
}
public static void main(String[] arguments) {
final Random random = new Random();
final DataSet dataSet = new DataSet(random);
final Line arbitraryLine1 = new Line(random, dataSet.indices);
final Line arbitraryLine2 = new Line(random, dataSet.indices);
final Line arbitraryLineM = new Line(random, dataSet.indices);
dataSet.findClosest(arbitraryLine1);
dataSet.findClosest(arbitraryLine2);
dataSet.findClosest(arbitraryLineM);
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... int-arrays