Getting unique numbers from two arrays

时光毁灭记忆、已成空白 提交于 2020-01-15 05:26:09

问题


If I have a couple of NSArrays filled with ints, or NSNumbers, like so:

A: { 12, 23, 45, 56, 67, 78, 99, 234 }
B: { 12, 56, 78, 99, 454, 512 }

How do I output an array with numbers that are in A but not in B, like

{ 23, 45, 67, 234 }

回答1:


What you are tying to do is purely a set operation. So you can use NSSet here. You should do minusSet: to get the result you want.

NSMutableSet *resultSet = [NSMutableSet setWithArray:A];
NSSet *setB = [NSSet setWithArray:B];

// This is what you need!
[resultSet minusSet:setB];

Array *result = [resultSet allObjects];



回答2:


Create an NSMutableArray called C. Do a loop over A that tries to find each of its elements within B (using [B containsObject:elemOfA], which just sends the -isEqual:elemOfA message to each member of B). If an element is found, do nothing; if an element isn't found, add it to C.



来源:https://stackoverflow.com/questions/7207805/getting-unique-numbers-from-two-arrays

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