重複する要素を取り除く
Posted feedbacks - Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #import <Foundation/Foundation.h>
@interface NSArray (UniqueElements)
- (NSArray*)uniqueElements;
@end
@implementation NSArray (UniqueElements)
- (NSArray*)uniqueElements
{
NSMutableDictionary* dic = [NSMutableDictionary dictionary];
for (id obj in self) {
NSNumber* n = [dic objectForKey:obj];
if (n) {
[dic setObject:[NSNumber numberWithInteger:[n intValue] + 1] forKey:obj];
} else {
[dic setObject:[NSNumber numberWithInteger:1] forKey:obj];
}
}
NSMutableArray* result = [NSMutableArray array];
for (id obj in self) {
NSNumber* n = [dic objectForKey:obj];
if ([n intValue] == 1) [result addObject:obj];
}
return result;
}
@end
int main(int argc, char** argv)
{
NSAutoreleasePool* pool = [NSAutoreleasePool new];
NSArray* array = [NSArray arrayWithObjects:@"a", @"b", @"c", @"b", @"d", @"a", @"d", @"e", nil];
NSLog(@"%@", array);
NSLog(@"%@", [array uniqueElements]);
[pool release];
return 0;
}
|


にしお
#3412()
Rating1/1=1.00
これはアレイのuniqの派生問題です。 リストとかアレイという言葉は言語によってまちまちの意味で使われているので、 「配列のようなもの」という漠然とした意味にとって構いません。
[ reply ]