0

I have an array with 5 CGPoints (v0, v1, v2, v3, v4) which are the vertex of the shape implemented like this:

_arrayVertex = [[NSMutableArray alloc] initWithObjects:[NSValue valueWithCGPoint:v0], [NSValue valueWithCGPoint:v1], [NSValue valueWithCGPoint:v2], [NSValue valueWithCGPoint:v3], [NSValue valueWithCGPoint:v4], nil];

Then, I calculate the area with those points:

- (float)calculateArea {

    float area = 0;
    int N = (int)_arrayVertex.count;

    for (int i = 0; i < N-1; i++) {

        float term = ([_arrayVertex[i] CGPointValue].x * [_arrayVertex[i+1 % N] CGPointValue].y -
                  [_arrayVertex[i+1 % N] CGPointValue].x * [_arrayVertex[i] CGPointValue].y)/2.0;

        area += term;
    }

    return fabsf(area);

}

Is the area correctly calculated? Am I missing something?. Thank you in advance.

iDec
  • 707
  • 2
  • 8
  • 16

1 Answers1

2

sbim:

- (float)calculateArea {

    float area = 0;
    int N = (int)_arrayVertex.count;

    for (int i = 0; i < N; i++) {

        float term = ([_arrayVertex[i] CGPointValue].x * [_arrayVertex[(i+1) % N] CGPointValue].y -
              [_arrayVertex[(i+1) % N] CGPointValue].x * [_arrayVertex[i] CGPointValue].y)/2.0;

        area += term;
    }

    return fabsf(area);

} 
NoonanRosenblum
  • 503
  • 6
  • 19
  • Return the same value as using modulo – iDec Feb 26 '16 at 11:59
  • Okay my mistake. I think the correct thing is to loop from 0 to N, and keep the modulo. I edited my answer. – NoonanRosenblum Feb 26 '16 at 12:25
  • It will crash, since you have 5 objects in the array and the value of N is 6, when i=N it will throw you an exception – iDec Feb 26 '16 at 12:48
  • if _arrayVertex contains 5 objects then _arrayVertex.count gives you 6 ? – NoonanRosenblum Feb 26 '16 at 12:58
  • My bad, I meant that N will return 5, but the array starts at 0 so when i = 5, in the position 5 of the array there's nothing, since the points are in the positions 0, 1, 2, 3 and 4. – iDec Feb 26 '16 at 13:01
  • if N = 5, then i should take the values 0 1 2 3 4; and (i+1) should take the values 1 2 3 4 5, and (i+1)%N should take the values 1 2 3 4 0. As the code is using i and (i+1)%N to access to the element, this should work, I hope ^^ – NoonanRosenblum Feb 26 '16 at 13:10
  • You were right, but I missed one silly thing, the parenthesis. Without it xCode throws the index beyond bounds exception so add it to your answer and it'll work correctly. Thank you! – iDec Feb 26 '16 at 13:15
  • woop haha my bad also. It was so clear in my head that I did not even see they were missing from the beginning. We finaly solved it together – NoonanRosenblum Feb 26 '16 at 13:19
  • Yeah those little mistakes always make us crazy, thank you! – iDec Feb 26 '16 at 13:20