The Interesting polygon challenge
Below we will define an n
-interesting polygon. Your task is to find the area of a polygon for a given n
.
A 1
-interesting polygon is just a square with a side of length 1
. An n
-interesting polygon is obtained by taking the n - 1
-interesting polygon and appending 1
-interesting polygons to its rim, side by side. You can see the 1
-, 2
-, 3
– and 4
-interesting polygons in the picture below.
Interesting polygon examples:
Example 1:
For n = 2
, the output should be: shapeArea(n) = 5
.
Example 2:
For n = 3
, the output should be: shapeArea(n) = 13
.
Example 3:
For n = 4
, the output should be: shapeArea(n) = 25
.
Example 4:
For n = 5
, the output should be: shapeArea(n) = 41
.
Example 5:
For n = 6
, the output should be: shapeArea(n) = 61
.
Example 6:
For n = 7
, the output should be: shapeArea(n) = 85
.
Illustration?
The Interesting polygon problem is a challenge that appears at CodeSignal and it tests the developer’s skills in using the array smartly,
Solutions
In the following section, I will illustrate some solutions for this challenge.
Solution c#
int InterestingPolygon(int n) { if (n == 1) { return 1; } if (n == 2) { return 5; } if (n == 3) { return 13; } return InterestingPolygonMethod(n - 1) + (8 + 4 * (n - 3)); }
Solution javascript
function interestingPolygon(n) { if (n == 1) { return 1; } if (n == 2) { return 5; } if (n == 3) { return 13; } return interestingPolygon(n - 1) + (8 + 4 * (n - 3)); } let res = interestingPolygon(5); console.log(res)
Conclusion:
The Interesting polygon challenge is one of the most well-known coding challenges in different software coding interviews. In this post, I introduced this challenge with examples and some solutions using c# language and Javascript You can find sample source codes at github Enjoy…!!!
I can help you to build such software tools/snippets, you contact me from her
Excellent solutions, big thanks
I hope if you can add solutions using go language
Thank you for your comment
I will try to add more solutions using go and other languages