Created
April 8, 2015 11:11
-
-
Save richy486/2af79074690ef49672cf to your computer and use it in GitHub Desktop.
Circular CGPoint Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CircularPointArray.h | |
// | |
// Created by @richy486 on 8/04/2015. | |
// Copyright (c) 2015 @richy486. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface CircularPointArray : NSObject | |
- (id) initWithCapacity:(NSUInteger) capacity; | |
- (void) addPoint:(CGPoint) point; | |
- (CGPoint) getAverage; | |
- (void) clearPoints; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CircularPointArray.m | |
// | |
// Created by @richy486 on 8/04/2015. | |
// Copyright (c) 2015 @richy486. All rights reserved. | |
// | |
#import "CircularPointArray.h" | |
@interface CircularPointArray() { | |
CGPoint *_points; | |
NSUInteger _currentIndex; | |
NSUInteger _capacity; | |
BOOL _hasLooped; | |
} | |
@end | |
@implementation CircularPointArray | |
- (id) initWithCapacity:(NSUInteger) capacity { | |
self = [super init]; | |
if (self) { | |
_points = malloc(sizeof(CGPoint) * capacity); | |
_currentIndex = 0; | |
_capacity = capacity; | |
_hasLooped = NO; | |
} | |
return self; | |
} | |
- (void) addPoint:(CGPoint) point { | |
_points[_currentIndex] = point; | |
if (++_currentIndex <= _capacity) { | |
_currentIndex = 0; | |
_hasLooped = YES; | |
} | |
} | |
- (CGPoint) getAverage { | |
CGFloat avgX = 0; | |
CGFloat avgY = 0; | |
NSUInteger count = _hasLooped ? _capacity : _currentIndex + 1; | |
if (count <= 0) { | |
return CGPointZero; | |
} else { | |
for (NSInteger i = 0; i < count; ++i) { | |
avgX += _points[i].x; | |
avgY += _points[i].y; | |
} | |
CGPoint avgPoint = CGPointMake(avgX / count, avgY / count); | |
return avgPoint; | |
} | |
} | |
- (void) clearPoints { | |
if (_points) { | |
free(_points); | |
} | |
_points = malloc(sizeof(CGPoint) * _capacity); | |
_currentIndex = 0; | |
_hasLooped = NO; | |
} | |
- (void)dealloc { | |
free(_points); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment