Skip to content

Instantly share code, notes, and snippets.

@rr-codes
Created August 31, 2018 05:37
Show Gist options
  • Save rr-codes/a32cf56a8a9b272456148e5db7f6749c to your computer and use it in GitHub Desktop.
Save rr-codes/a32cf56a8a9b272456148e5db7f6749c to your computer and use it in GitHub Desktop.
Different methods for arbitrary n-dimensional points in Java
package practice.eecs1021;
class Point {
private double[] coord;
Point (double... coord) { this.coord = coord; }
// get value from index
private double getValue(int index) { return coord[index]; }
// get size of array
private int getSize() { return coord.length; }
// get distance from coordNew
double getDistanceFrom(Point coordNew) {
double sum = 0;
if (coord.length != coordNew.getSize()) return 0;
else {
for (int i = 0; i < coord.length; i++) {
double diff = Math.pow(coord[i] - coordNew.getValue(i), 2);
sum += diff;
}
return Math.sqrt(sum);
}
}
// get hypoteneuse
double getHyp() {
double sum = 0;
for (double aCoord : coord) {
sum += Math.pow(aCoord, 2);
}
return Math.sqrt(sum);
}
}
public class Main {
public static void main(String[] args) {
Point start = new Point(1, 2, 3);
Point end = new Point(0, 0, 1);
System.out.println(start.getDistanceFrom(end));
System.out.println(start.getHyp());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment