cog/Utils/NSArray+ShuffleUtils.m

70 lines
1.6 KiB
Matlab
Raw Normal View History

2008-02-16 02:46:37 +00:00
//
// Pair.m
// Cog
//
// Created by Eric Hanneken on 2/13/08.
// Copyright 2008 Vincent Spader. All rights reserved.
//
#import "NSArray+ShuffleUtils.h"
@implementation NSArray (ShuffleUtils)
/*
* Generates an array of random long integers in the range
* 0 to (2**31) - 1. The length of the array is determined
* by the count parameter.
*/
+ (NSArray*)arrayWithRandomLongs:(NSUInteger)count {
2008-02-16 02:46:37 +00:00
NSMutableArray* randomLongs = [NSMutableArray arrayWithCapacity:count];
NSUInteger i;
for(i = 0; i < count; ++i) {
2008-02-16 02:46:37 +00:00
[randomLongs addObject:[NSNumber numberWithLong:random()]];
}
2008-02-16 02:46:37 +00:00
return randomLongs;
}
+ (NSArray*)zipArray:(NSArray*)x withArray:(NSArray*)y {
2008-02-16 02:46:37 +00:00
NSUInteger xCount = [x count];
NSUInteger yCount = [y count];
NSUInteger minCount = (xCount < yCount) ? xCount : yCount;
NSMutableArray* pairs = [NSMutableArray arrayWithCapacity:minCount];
NSUInteger i;
for(i = 0; i < minCount; ++i) {
NSArray* p = @[[x objectAtIndex:i], [y objectAtIndex:i]];
2008-02-16 02:46:37 +00:00
[pairs addObject:p];
}
2008-02-16 02:46:37 +00:00
return pairs;
}
+ (NSArray*)unzipArray:(NSArray*)pairs {
2008-02-16 02:46:37 +00:00
NSMutableArray* first = [NSMutableArray arrayWithCapacity:[pairs count]];
NSMutableArray* second = [NSMutableArray arrayWithCapacity:[pairs count]];
for(NSArray* pair in pairs) {
2008-02-16 02:46:37 +00:00
[first addObject:[pair first]];
[second addObject:[pair second]];
}
return @[first, second];
}
2008-02-16 02:46:37 +00:00
/*
* Compares two pairs by their first objects.
*/
- (NSComparisonResult)compareFirsts:(id)y {
2008-02-16 02:46:37 +00:00
return [[self first] compare:[y first]];
}
- (id)first {
2008-02-16 02:46:37 +00:00
return [self objectAtIndex:0];
}
- (id)second {
2008-02-16 02:46:37 +00:00
return [self objectAtIndex:1];
}
@end