problem link:https://www.codechef.com/problems/R303
solution link:https://www.codechef.com/viewsolution/12854127
please help in finding the problem with my solution which is not being accepted
If I am not wrong, the question gives you co-ordinates of polygon and asks area. I wrote a similar program last year, so have a look at my code in JAVA.
[PS - THIS PROGRAM WAS WRITTEN IN BLUEJ FOR MY OWN PURPOSES (helping in school homework ). THE SYNTAX ETC. MAY NOT BE VALID ON CODECHEF IDE, SO SEE ACCORDINGLY.]
import java.util.*;
class FunctionsArea
{
double area (int n)
{
System.out.println ("Enter x co-ordinates");
int i,j,k,l;
double area1=0.0 , area2=0.0;
Scanner sc = new Scanner(System.in);
double x[]= new double[n];
double y[]= new double[n];
for(i=0;i < n;++i)
x[i]= sc.nextDouble();
System.out.println ("Enter y co-ordinates");
for (j=0;j < n;++j)
y[j] = sc.nextDouble();
for (k=0;k< n-1;k++)
area1+= x[k]*y[k+1];
for (l=0;l< n-1;l++)
area2 += x[l+1]*y[l];
area1= area1+ x[n-1]*y[0];
area2+=x[0]*y[n-1];
double area = (area1 - area2)/2;
double ActualArea = Math.abs(area);
System.out.println ("Area1 is "+area1+" "+"Area 2 is"+area2);
return ActualArea;
}
public void main()
{
Scanner sc = new Scanner(System.in);
System.out.println ("Enter number of sides");
double area1,area2;
int n =sc.nextInt();
double NeededArea = area(n);
System.out.println ("The area of figure is"+" "+NeededArea);
}
}
Area 1 and Area 2 were for debugging purposes, with Area= abs((Area1-Area2)/2)
Now, coming to your program, have a look at the test cases-
Compilation Successful
Input (stdin)
2
3
0
0
1
1
2
1
3
1
1
-1
1
-1
0
Your Output
357180570621342400.0
357180570621342400.0
The above was result by compiling in hackerrank compiler, but codechef compiler also gave similar weird result. I suspect that the problem is in the formula-
while(c<=n)
{
if(i+1!=n)
s+=((x[i]*y[i+1])-(y[i]*x[i+1]));
else
s+=((x[i]*y[0])-(y[i]*x[0]));
i++;
c++;
}
c was 0. When the value of c is n, THE VALUE OF i IS ALSO N. And your if else EXECUTES.
n+1!=n = true
So, it uses a value which does not exist (i don’t know why array out of bound error isn’t thrown here!) but basically the thing is, a[n] doesn’t exist so any garbage value is assigned to it in the formula and its causing the error. That’s what i think.
thanks a lot.
Happy to help dear,