简体   繁体   English

如何在Objective-c中比较各种NSArray?

[英]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. 我的代码包含四个NSArray ,每个NSArray包含两个对象,这些对象表示屏幕上任意位置的XY坐标。 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? 在这种情况下, isEqualTo:方法可以提供帮助吗?

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. 一种方法是维护NSDictionary ,将数组中的坐标用作键,然后为看到相同坐标时递增的每个坐标(即键)维护一个计数器。

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. 请注意,此代码未经测试,必须根据您的类型和变量名称进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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