Here is a quick Monday morning challenge...
Write a function or program in the least number of bytes that:
- Takes as input a list of
[x,y]
coordinates - Takes as input a list of the
[x,y]
coordinates' respective masses - Outputs the calculated center of mass in the form of
[xBar,yBar]
.
Note:
- Input can be taken in any form, as long as an array is used.
The center of mass can be calculated by the following formula:
In plain English...
- To find
xBar
, multiply each mass by its respective x coordinate, sum the resulting list, and divide it by the sum of all masses. - To find
yBar
, multiply each mass by its respective y coordinate, sum the resulting list, and divide it by the sum of all masses.
Trivial Python 2.7 example:
def center(coord, mass):
sumMass = float(reduce(lambda a, b: a+b, mass))
momentX = reduce(lambda m, x: m+x, (a*b for a, b in zip(mass, zip(*coord)[0])))
momentY = reduce(lambda m, y: m+y, (a*b for a, b in zip(mass, zip(*coord)[1])))
xBar = momentX / sumMass
yBar = momentY / sumMass
return [xBar, yBar]
Test Cases:
> center([[0, 2], [3, 4], [0, 1], [1, 1]], [2, 6, 2, 10])
[1.4, 2.0]
> center([[3, 1], [0, 0], [1, 4]], [2, 4, 1])
[1.0, 0.8571428571428571]
This is code-golf, so the least number of bytes wins!
[x,y,m],[x,y,m]...
? \$\endgroup\$[(x1,y1,m1), (x2,y2,m2)]
, e.g. a list of tuples? Or doesn't it matter whether the arguments are tuples, lists or arrays? What about three lists/arrays? \$\endgroup\$