Last active
May 10, 2022 16:58
-
-
Save gosoccerboy5/0a16e3514fbadf8732e749e5b27dabfb to your computer and use it in GitHub Desktop.
Find the perimeter or area of a polygon from a set of points
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* area(Array<Array<Number>> ...list) | |
* | |
* takes in a set of points (in clockwise or counterclockwise order) and returns the area of the polygon the points form | |
* example call: `area([3, 10], [9, 7], [11, 2], [2, 2]);` | |
**/ | |
function area(...list) { | |
let total = 0; | |
for (let index = 0; index < list.length; index++) { | |
const point = list[index]; | |
let nextPoint = list[index+1]; | |
nextPoint ??= list[0]; | |
total += (point[0] * nextPoint[1] - point[1] * nextPoint[0]); | |
} | |
return Math.round(Math.abs(total/2) * 100)/100; | |
} | |
area([3, 10], [9, 7], [11, 2], [2, 2]); // 48 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* perim(Array<Array<Number>> ...list) | |
* | |
* takes in a set of points (in clockwise or counterclockwise order) and returns the perimeter of the polygon it forms | |
* example call: `perim([-4, -2], [2, -5], [-4, -9]);` | |
**/ | |
function perim(...list) { | |
let total = 0; | |
for (let index = 0; index < list.length; index++) { | |
const point = list[index]; | |
let nextPoint = list[Number(index)+1]; | |
nextPoint ??= list[0]; | |
total += Math.sqrt((point[0]-nextPoint[0])**2 + (point[1]-nextPoint[1])**2); | |
} | |
return Math.round(total*100)/100; | |
} | |
perim([-4, -2], [2, -5], [-4, -9]); // 20.92 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment