Closest-pair problem/Objective-C: Difference between revisions
m
Fixed syntax highlighting.
m (Fixed syntax highlighting.) |
|||
(One intermediate revision by one other user not shown) | |||
Line 4:
{{works with|Cocoa}}
<
#import <math.h>
Line 10:
double xCoord, yCoord;
}
+ (
- (
- (double)x;
- (double)y;
Line 21:
@implementation Point
+ (
return
}
- (
if (
xCoord = x;
}
return self;
}
Line 52 ⟶ 51:
else return NSOrderedSame;
}
@end</
<
+ (NSArray *)closestPairSimple: (NSArray *)pts;
+ (NSArray *)closestPair: (NSArray *)pts;
Line 64 ⟶ 63:
+ (NSArray *)closestPairSimple: (NSArray *)pts {
if ( [pts count] < 2 ) return @[ @HUGE_VAL ];
int i, j;▼
double c = [ pts[0] dist: pts[1] ];
NSArray *r = @[ @(c), pts[0], pts[1] ];
for(int j=i+1; j < [pts count]; j++) {▼
double t = [ pts[i] dist: pts[j] ];
▲ for(j=i+1; j < [pts count]; j++) {
if ( t < c ) {
c = t;
r = @[
}
}
Line 95 ⟶ 85:
+ (NSArray *)closestPairPriv: (NSArray *)xP and: (NSArray *)yP {
if ( [xP count] <= 3 ) {
Line 104 ⟶ 91:
} else {
int midx = ceil([xP count]/2.0);
NSArray *pL = [xP subarrayWithRange: NSMakeRange(0, midx)];
NSArray *pR = [xP subarrayWithRange: NSMakeRange(midx, [xP count] - midx)];
NSMutableArray *yL = [[NSMutableArray alloc] init];
NSMutableArray *yR = [[NSMutableArray alloc] init];
double middleVLine = [pL[
for(int i=0; i < [yP count]; i++) {
if (
[yL addObject:
} else {
[yR addObject:
}
}
NSArray *minR = [ClosestPair closestPairPriv: pR and: yR];
NSArray *minL = [ClosestPair closestPairPriv: pL and: yL];
NSMutableArray *minDist = [ClosestPair minBetween: minR and: minL];
NSMutableArray *joiningStrip = [NSMutableArray arrayWithCapacity: [xP count]];
for(int i=0; i < [yP count]; i++) {
if ( fabs(
[joiningStrip addObject:
}
}
NSMutableArray *tDist = minDist;
int nP = [joiningStrip count];
for(int i=0; i < (nP - 1); i++) {
int k = i + 1;
while( (k < nP) &&
( (
double d = [joiningStrip[i] dist: joiningStrip[k]];
}
k++;
}
}
return tDist;
}
Line 148 ⟶ 131:
+ (id)minBetween: (id)minA and: (id)minB {
if (
▲ [[minB objectAtIndex: 0] doubleValue] ) {
return minA;
} else {
Line 156 ⟶ 138:
}
@end</
'''Testing'''
<
int main()
{
@autoreleasepool {
NSMutableArray *p = [[NSMutableArray alloc] init];
srand(0);
for(int i = 0; i < NP; i++) {
[p addObject:
[Point x: 20.0*((double)rand()/(RAND_MAX+1.0)) - 10.0
y: 20.0*((double)rand()/(RAND_MAX+1.0)) - 10.0]
];
}
//NSArray *r1 = [ClosestPair closestPairSimple: p];
NSArray *r2 = [ClosestPair closestPair: p];
//NSLog(@"%lf",
NSLog(@"%lf",
}
return EXIT_SUCCESS;
}</
Timing (with the <tt>time</tt> command):
|