Skip to content

Instantly share code, notes, and snippets.

@pistatium
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pistatium/46529d31cfa3c5281ba3 to your computer and use it in GitHub Desktop.
Save pistatium/46529d31cfa3c5281ba3 to your computer and use it in GitHub Desktop.
多角形の面積を計算する的な
/**
* Copyright (c) 2014 pistatium
*
* This software is released under the MIT License.
*
* http://opensource.org/licenses/mit-license.php
*/
import java.util.*;
import java.lang.Math;
/**
* 多角形の面積を計算する用のクラス
*
*/
public class PolyArea {
private static class Point {
public double x;
public double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
private ArrayList<Point> points;
public PolyArea() {
points = new ArrayList<Point>();
}
public void add(double x, double y) {
points.add(new Point(x, y));
}
/**
* 外積を使って面積を計算する
*/
public double calcArea() {
int count = points.size();
// 3点以下は0を返す
if (count < 3) {
return 0.0;
}
double sum = 0.0;
for (int i = 0; i < count; i++) {
int i_next = (i + 1) % count;
int i_next2 = (i + 2) % count;
Point p1 = points.get(i);
Point p2 = points.get(i_next);
Point p3 = points.get(i_next2);
sum += (p1.x - p3.x) * p2.y;
}
return Math.abs(0.5 * sum);
}
}
@sakebook
Copy link

Good code! I found this!

@pistatium
Copy link
Author

    PolyArea area = new PolyArea();
    area.add(0,0);
    area.add(3,0);
    area.add(3,3);
    area.add(0,3);
    System.out.println(area.calc());

9.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment