开发者

Elegant calculation of array elements

开发者 https://www.devze.com 2023-04-01 01:34 出处:网络
I would like to do some calculations and comparisons inside my array assuming my array is simple as: NSMutableArray *array;

I would like to do some calculations and comparisons inside my array

assuming my array is simple as:

NSMutableArray *array;   
array = [[NSMutableArray alloc] init]; 
[array addObject:[NSNumber numberWithInt:1]]; 
[array addObject:[NSNumber numberWithInt:2]]; 
[array addObject:[NSNumber numberWithInt:2]]; 
[array addObject:[NSNumber numberWithInt:3]]; 
[array addObject:[NSNumber numberWithInt:2]]; 

What would be an 开发者_Go百科elegant and clever way to check if a number repeats itself 2,3,4 or 5 times inside this array. (looking for something smart and dynamic....)


If the numbers are only in range 0 to 10 then you should have an array of 11 elements, named counts. The ith element in the array is the number of times i appears in the original array. Filling in the count array is straightforward: a single loop through your initial array (a), on each iteration increment counts[a[i]].

The number i repeats itself counts[i] times. No if's :)


You don't have to loop through things yourself if you just want to know how many times each object shows up. That bit is really easy:

NSMutableArray *array;   
array = [[NSMutableArray alloc] init]; 
[array addObject:[NSNumber numberWithInt:1]]; 
[array addObject:[NSNumber numberWithInt:2]]; 
[array addObject:[NSNumber numberWithInt:2]]; 
[array addObject:[NSNumber numberWithInt:3]]; 
[array addObject:[NSNumber numberWithInt:2]]; 

NSCountedSet *counts = [[NSCountedSet alloc] initWithArray:array]

NSLog(@"%d", [counts countForObject:[NSNumber numberWithInt:2]]); // logs 3

[array release];
[counts release];


Not sure if this counts as elegant in your mind, but you could always subclass NSMutableArray to add code that counts occurrences of specific numbers as they are added/removed. The documentation for NSMutableArray says that there is rarely a good reason to subclass it, but it does give examples of when it might make sense, including this one:

Acquiring more information about what is happening to the collection (for example, statistics gathering).

I would consider what you are doing as a form of statistics gathering, wouldn't you?

0

精彩评论

暂无评论...
验证码 换一张
取 消