Skip to content

Commit 238f876

Browse files
committed
feat: add polygon inside circle solution
1 parent f3a0e70 commit 238f876

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Calculate the Area of a Regular n Sides Polygon Inside a Circle of Radius r
2+
3+
## Description
4+
5+
Write the following function:
6+
7+
```js
8+
function areaOfPolygonInsideCircle(circleRadius, numberOfSides)
9+
```
10+
11+
It should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes through all the vertices of the polygon (such circle is called **circumscribed** circle or **circumcircle**). The answer should be a number rounded to 3 decimal places.
12+
13+
Input :: Output Examples
14+
15+
```js
16+
areaOfPolygonInsideCircle(3, 3); // returns 11.691
17+
18+
areaOfPolygonInsideCircle(5.8, 7); // returns 92.053
19+
20+
areaOfPolygonInsideCircle(4, 5); // returns 38.042
21+
```
22+
23+
**Note:** if you need to use Pi in your code, use the native value of your language unless stated otherwise.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
const areaOfPolygonInsideCircle = (cRadius, nSides) => {
2+
const angle = (180 * (nSides - 2)) / nSides / 2;
3+
const apotema = cRadius * Math.sin(Math.PI * (angle / 180));
4+
const side = cRadius * Math.cos(Math.PI * (angle / 180)) * 2;
5+
const area = (nSides * side * apotema) / 2;
6+
return Number(area.toFixed(3));
7+
};
8+
9+
module.exports = areaOfPolygonInsideCircle;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const areaOfPolygonInsideCircle = require('./solution');
2+
3+
describe('Area of polygon inside circle', () => {
4+
const testCases = [
5+
{
6+
input: [5.8, 7],
7+
output: 92.053,
8+
},
9+
{
10+
input: [3, 3],
11+
output: 11.691,
12+
},
13+
{
14+
input: [4, 5],
15+
output: 38.042,
16+
},
17+
{
18+
input: [2, 4],
19+
output: 8,
20+
},
21+
{
22+
input: [2.5, 5],
23+
output: 14.86,
24+
},
25+
];
26+
27+
it('should return a number type', () => {
28+
expect(typeof areaOfPolygonInsideCircle(5.8, 7)).toBe('number');
29+
});
30+
31+
it.each(testCases)('should return the correct output', ({ input, output }) => {
32+
expect(areaOfPolygonInsideCircle(...input)).toBe(output);
33+
});
34+
});

0 commit comments

Comments
 (0)