Compare two NSArrays and return number of differences

有些话、适合烂在心里 提交于 2019-11-29 14:09:32

问题


How can I take two NSArrays, compare them, then return the number of differences, preferably the number of different objects, for example:

Array 1: one two three

Array 2: two four one

I would like that to return "1"


回答1:


You can do this by using an intermediate NSMutableArray:

NSArray *array1 = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];
NSArray *array2 = [NSArray arrayWithObjects:@"Two", @"Four", @"One", nil];
NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];

With that way, only common elements will be removed.




回答2:


I found that the answer above didn't take arrays of differing size into account. If you do it as above, you should check to see which array.count is smaller and

[largerArray removeObjectsInArray:shorterArray];

OR

I made them both NSSets and then compared.

[set1 isEqualToSet:set2];

That way size and order are both dealt with properly! (I didn't need to know the number of differences)



来源:https://stackoverflow.com/questions/2939348/compare-two-nsarrays-and-return-number-of-differences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!