简体   繁体   中英

How to compare various NSArrays in Objective-c?

My code contains four NSArray s, each of which contains two objects which represent XY-Coordinate at any point on the screen. Two or more arrays may contain same set of coordinates. I need to find the coordinate which has highest number of repetition among these four arrays. Can the isEqualTo: method help in this case?

One approach would be to maintain an NSDictionary , use the coordinates in your arrays as keys and then maintain a counter for each coordinate (ie key) that you increment whenever you see the same coordinate.

This could look somewhat like this:

NSMutableDictionary *coordinateCount = [[NSMutableDictionary alloc] init];
for (int i = 0; i < coordinates.length; i++) { // do this loop for each of your 4 arrays
   Coordinate *c = coordinates[i];
   if ([coordinateCount containsKey:c]) {
      NSInteger count = [coordinateCount[c] integerValue];
      count++;
      coordinateCount[c] = @(count);
   }
   else {
      coordinateCount[c] = @(1);
   }
}

// now you can retrieve the max count value from all collected values

Note that this code is not tested and has to be adjusted depending on your types and variable names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM