Last active
August 31, 2018 06:16
-
-
Save rr-codes/1128703f3c700455c09a24e30373f464 to your computer and use it in GitHub Desktop.
Different methods for arbitrary n-dimensional points in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Point { | |
public double[] coord; | |
Point (double... coord) { this.coord = coord; } | |
public double getValue(int index) { return coord[index]; } | |
public int getSize() { return coord.length; } | |
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); | |
} | |
} | |
double getHyp() { | |
double sum = 0; | |
for (double aCoord : coord) sum += Math.pow(aCoord, 2); | |
return Math.sqrt(sum); | |
} | |
} | |
class Polygon { | |
public Point[] points; | |
Polygon (Point... points) { this.points = points; } | |
private double sum = 0; | |
double getArea() { | |
double[] x = new double[points.length+1]; | |
double[] y = new double[points.length+1]; | |
for (int i = 0; i < points.length; i++) { | |
x[i] = points[i].getValue(0); | |
y[i] = points[i].getValue(1); | |
} | |
x[points.length] = x[0]; | |
y[points.length] = y[0]; | |
for (int j = 0; j < points.length; j++) { | |
sum += x[j]*y[j+1] - x[j+1]*y[j]; | |
} | |
return sum/2; | |
} | |
} | |
public class AwesomeNess { | |
public static void main(String[] args) { | |
Point pt1 = new Point(0, 0, 1); | |
Point pt2 = new Point(1, 0, 1); | |
Point pt3 = new Point(1, 1); | |
Point pt4 = new Point(0, 1); | |
Polygon polygon = new Polygon(pt1, pt2, pt3, pt4); | |
System.out.println(pt2.getDistanceFrom(pt1)); | |
System.out.println(pt1.getHyp()); | |
System.out.println(polygon.getArea()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment