Find the Centroid of a Polygon
Mathematica, 23 bytes
RegionCentroid@*Polygon
Take THAT, Jelly!
Edit: One does not simply beat Jelly...
Explanation
Polygon
Generate a polygon with vertices at the points specified.
RegionCentroid
Find the centroid of the polygon.
Jelly, 25 24 22 21 18 bytes
S×3÷@×"
ṙ-żµÆḊçS€S
Applies the formula shown in the problem.
Saved 3 bytes with help from @Jonathan Allan.
Try it online! or Verify all test cases.
Explanation
S×3÷@×" Helper link. Input: determinants on LHS, sum of pairs on RHS
S Sum the determinants
×3 Multiply by 3
×" Vectorized multiply between determinants and sums
÷@ Divide that by the determinant sum multipled by 3 and return
ṙ-żµÆḊçS€S Main link. Input: 2d list of points
ṙ- Rotate the list of points by 1 to the right
ż Interleave those with the original points
This creates all overlapping slices of length 2
µ Start new monadic chain
ÆḊ Get the determinant of each slice
S€ Get the sum of each slice (sum of pairs of points)
ç Call the helper link
S Sum and return
J, 29 bytes
2+/@(+/\(*%3*1#.])-/ .*\)],{.
Applies the formula shown in the problem.
Usage
f =: 2+/@(+/\(*%3*1#.])-/ .*\)],{.
f 0 0 , 1 0 , 1 1 ,: 0 1
0.5 0.5
f _15.21 0.8 , 10.1 _0.3 ,: _0.07 23.55
_1.72667 8.01667
f _39 _55.94 , _56.08 _4.73 , _72.64 12.12 , _31.04 53.58 , _30.36 28.29 , 17.96 59.17 , 0 0 , 10 0 , 20 0 , 148.63 114.32 , 8.06 _41.04 ,: _41.25 34.43
5.80105 15.0674
Explanation
2+/@(+/\(*%3*1#.])-/ .*\)],{. Input: 2d array of points P [[x1 y1] [x2 y2] ...]
{. Head of P
] Get P
, Join, makes the end cycle back to the front
2 The constant 2
2 \ For each pair of points
-/ .* Take the determinant
2 +/\ Sum each pair of points
* Multiply the sum of each pair by its determinant
% Divide each by
1#.] The sum of the determinants
3* Multiplied by 3
+/@ Sum and return