Mam kod obliczający odległość między punktami na płaszczyźnie:
public class Point {
private double x;
private double y;
public static Point zero = new Point();
public Point() {
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
@Override // adnotacja
public String toString() {
return "[" + x + "," + y + "]";
}
public double distance(Point x) {
return distance(this, x);
}
public static double distance(Point x, Point y) {
double ret=0;
ret += Math.pow(x.x - y.x, 2);
ret += Math.pow(x.y - y.y, 2);
return Math.sqrt(ret);
}
public static void main(String[] args) {
Point a = new Point(2, 3);
Point b = new Point(4, 1);
System.out.println(a.distance (Point.zero));
System.out.println(Point.distance(a, Point.zero));
System.out.println(a.distance(a,b));
System.out.println(Point.distance(a, b));
}
}
'''
na tej podstawie zrobiłem kod obliczający odległość między punktami w przestrzeni 3d:
'''java
import java.util.Scanner;
public class PointSpace {
// private double [] z;
private double x;
private double y;
private double z;
public static PointSpace zero = new PointSpace();
public PointSpace() {
}
public PointSpace(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return "(" + x + "," + y + "," + z + ")";
}
public double distance(PointSpace x) {
return distance(this, x);
}
public static double distance(PointSpace x, PointSpace y) {
double ret = 0;
ret += Math.pow(x.x - y.x, 2);
ret += Math.pow(x.y - y.y, 2);
ret += Math.pow(x.z - y.z, 2);
return Math.sqrt(ret);
}
public static void main(String[] args) {
PointSpace a = new PointSpace(2, 2, 2);
PointSpace b = new PointSpace(4, 3, 2);
System.out.format("The distance between point a" + a + "and origin of coordinates is: %.2f\n", a.distance(PointSpace.zero));
System.out.format("The distance between point a" + b + "and origin of coordinates is: %.2f\n", b.distance(PointSpace.zero));
System.out.format("The distance between point a" + a + "and point b" + b + " is: %.2f", a.distance(a, b));
}
}
a jak to uogólnić, żeby mogło być dla dowolnej przestrzeni?
Proszę o wyrozumiałość, bo to pewnie proste, ale nie dla mnie... Dopiero raczkuję.
Próbowałem to zrobić tablicami, ale nie mogę sobie poradzić z konwersją...