19
1
Calculate the area of a polygon.
Inspired by this shoelace algorithm video.
Task
Your job is to create a program or function that calculates the area of a polygon. Program or function is defined according the the default definition in meta.
Input
You will receive the X and Y coordinates of each vertex of the polygon. You can take the input as a list of tuples ([[x1, y1], [x2, y2], etc]
), a matrix, or a flat list ([x1, y1, x2, y2, etc]
). Two lists containing x
and y
coordinates respectively are allowed as well. The vertices are numbered counterclockwise and the first vertex is the same as the last vertex provided, thus closing the polygon.
If you want you can take the input without the last vertex (so receive each coordinate just once).
You can assume that the edges of the polygons don't intersect. You can also assume that all vertices have integer coordinates.
Output
The area of the polygon. All standard output methods are allowed. If your language does not allow for float division and the solution would not be an integer, you are allowed to return a fraction. The fraction does not necessarily have to be simplified, so returning 2/4
would be allowed.
Winning criterium
Shortest code wins!
Test cases
[[4,4],[0,1],[-2,5],[-6,0],[-1,-4],[5,-2],[4,4]]
55
[[1,1],[0,1],[1,0],[1,1]]
0.5
1/2
Is input like
[x1, x2, x3], [y1, y2, y3]
allowed? – programmer5000 – 2017-06-14T13:34:07.713@programmer5000 and Martin Ender , yes, I'll edit it in :) – JAD – 2017-06-14T13:35:36.927
I agree, voted to reopen. – programmer5000 – 2017-06-14T13:53:01.787
1@flawr I made that a dupe of this. It is not really a dupe of its dupe target, which to apply the same method as here recursively would require finding the vertices that are crossing points and would require ordering the resulting subsets into counter-clockwise fashion - that seems much more complex. – Jonathan Allan – 2017-06-14T14:08:13.313