Languages: [πͺπΈ] EspaΓ±ol - [πΊπΈ] English
Since college, I was not encouraged to do programming challenges, until I got the invitation to CodeSign...
For further actions, you may consider blocking this person and/or reporting abuse
I think think there's an even easier solution:
I think this is more appropriate:
function shapeArea(n) {
return (1 + (n-1)*n) *2 - 1
}
Why do you think that formula ?
Did you solve it?
Hey buddy, can you explain your solution?
Yeah, that's exactly the beauty that I talk about code fights. You can learn from other solution.
I found this solution and just replaced the variables
function shapeArea(n) {
return 1 + 2 * n * (n-1)
//1 + 2 * 4 * (3) = 3*4=12*2=24+1=25
//1 + 2 * 3 * (2) = 2*3=6*2=12+1=13
//1 + 2 * 2 * (1) = 1*2=2*2=4+1=5
//1 + 2 * 1 * (0) = 0*1*=0*2=0+1=1
}
Hi! Would it be possible for someone to explain what's happening in the code? I'm a beginner to both code and maths. Any resources and tutorials would be appreciated too :)
There is no tutorial about this specific ploblem. You need learn other concepts like recursion and loops.
This function
shapeArea
is not important. It's used to measure the amount of time.Relevant things on this exercise is
x.loopShapeArea
,x.recursionShapeArea
andx.mathShapeArea
. Three of them solves the problem, but math is more efficient than others.But where did you get the 4 from & multiplying it ?
For example when I can recite something for 60 times in a min so if i recite for 100 mins i just do 60 * 100 to find out how many times I recite a line.
What was ur reasoning behind using the number 4 ? I am not clear on how I would go on solving this on my own. @
I'm using a technic learned in a subject Numerical Methods. You need reproduce step by steep and try to find something familiar between each interaction.
A square have 4 sides, that's why you need multiply the value by four.
But each side merge a point with other in the other side (red circle), you can't count both. That's why yo need subtract 4, one for each corner.
That's how I found this formula:
n * 4 - 4
On first and second iteration is difficult to see it... but next iterations can give you an idea about the solution.
Hope it helps.
the simpler way I think is:
Just rotate the grid view by 45ΒΊ and check the patterns
return n*n + (n-1)*(n-1);
It's more like:
I tried both solution
function shapeArea(n) {
var res = 1;
for(let i = 1; i < n; i++){
res = res + (i*4)
}
return res;
}
return n * ((n - 1) * 2) + 1;
n*(n*2*-1)-int((n*2-1/2)
this is the shortest valid solution :
int output = 1;
for (int i = 1; i <= n; i++) {
if (i != 1) {
output = output + 4 * (i - 1);
}
}
i tried both solution
function solution(n) {
return 2*n*(n-1) +1;
//return n*2+(n-1)*2
}