forked from ZigaSajovic/javaCalculus
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistance.java
More file actions
55 lines (45 loc) · 1.48 KB
/
Copy pathDistance.java
File metadata and controls
55 lines (45 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Distance {
private static double dotProduct(int[] pointA, int[] pointB, int[] pointC)
{
double[] AB = new double[2];
double[] BC = new double[2];
AB[0] = pointB[0] - pointA[0];
AB[1] = pointB[1] - pointA[1];
BC[0] = pointC[0] - pointB[0];
BC[1] = pointC[1] - pointB[1];
double dot = AB[0] * BC[0] + AB[1] * BC[1];
return dot;
}
public static double vecProduct(int[] pointA, int[] pointB, int[] pointC)
{
double[] AB = new double[2];
double[] AC = new double[2];
AB[0] = pointB[0] - pointA[0];
AB[1] = pointB[1] - pointA[1];
AC[0] = pointC[0] - pointA[0];
AC[1] = pointC[1] - pointA[1];
double cross = AB[0] * AC[1] - AB[1] * AC[0];
return cross;
}
private static double distance(int[] pointA, int[] pointB)
{
double d1 = pointA[0] - pointB[0];
double d2 = pointA[1] - pointB[1];
return Math.sqrt(d1 * d1 + d2 * d2);
}
public static double pointToLine(int[] pointA, int[] pointB, int[] pointC,
boolean isSegment)
{
double dist = vecProduct(pointA, pointB, pointC) / distance(pointA, pointB);
if (isSegment)
{
double dot1 = dotProduct(pointA, pointB, pointC);
if (dot1 > 0)
return distance(pointB, pointC);
double dot2 = dotProduct(pointB, pointA, pointC);
if (dot2 > 0)
return distance(pointA, pointC);
}
return Math.abs(dist);
}
}