forked from williamfiset/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TriangleArea.java
74 lines (56 loc) · 2.17 KB
/
TriangleArea.java
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* There is more than one way to take the area of a triangle, some are faster or more convenient in
* some situations.
*
* <p>Time Complexity: O(1)
*
* @author William Fiset, [email protected]
*/
package com.williamfiset.algorithms.geometry;
import static java.lang.Math.*;
import java.awt.geom.*;
public class TriangleArea {
// Given three sides of a triangle use Heron's formula
// to compute the area of the triangle.
public static double triangleArea(double side1, double side2, double side3) {
// Semi-perimeter
double s = (side1 + side2 + side3) / 2.0;
// Square root makes this method slower than the others
return sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
// Given three points a, b, c find the area of the triangle
public static double triangleArea(
double ax, double ay, double bx, double by, double cx, double cy) {
// Let v1 = <bx-ax, by-ay> and v2 = <cx-ax, cy-ay> be vectors
// Take the determinant of v1 and v2 to find the area of the
// parallelogram of the two vectors.
double v1_x = bx - ax;
double v1_y = by - ay;
double v2_x = cx - ax;
double v2_y = cy - ay;
// | v1_x v2_x |
// Determinant of | v1_y v2_y | is v1_x*v2_y - v2_x*v1_y
double determinant = v1_x * v2_y - v2_x * v1_y;
// Divide by two because we computed the area of the parallelogram
return abs(determinant) / 2.0;
}
// Given three points a,b,c find the area of the triangle
public static double triangleArea(Point2D a, Point2D b, Point2D c) {
return triangleArea(a.getX(), a.getY(), b.getX(), b.getY(), c.getX(), c.getY());
}
// The traditional triangle area formula
public static double triangleArea(double base, double height) {
return base * (height / 2.0);
}
// Example usage
public static void main(String[] args) {
Point2D a = new Point2D.Double(0, 1);
Point2D b = new Point2D.Double(2, 0);
Point2D c = new Point2D.Double(3, 4);
System.out.println(triangleArea(a, b, c));
double side1 = a.distance(b);
double side2 = a.distance(c);
double side3 = b.distance(c);
System.out.println(triangleArea(side1, side2, side3));
}
}