我有 2 个 nsarray,具有相同的值但顺序不同。
NSArray * array1 = {0,1,2,3}
NSArray * array2 = {2,3,1,0}
我需要一种方法来确定两个数组是否以不同的顺序具有相同的值。
有点儿
-(BOOL) isSameValues:(NSArray*)array1 and:(NSArray*)array2;
我有 2 个 nsarray,具有相同的值但顺序不同。
NSArray * array1 = {0,1,2,3}
NSArray * array2 = {2,3,1,0}
我需要一种方法来确定两个数组是否以不同的顺序具有相同的值。
有点儿
-(BOOL) isSameValues:(NSArray*)array1 and:(NSArray*)array2;
You can use NSCountedSet
for that purpose:
- (BOOL)isSameValues:(NSArray*)array1 and:(NSArray*)array2
{
NSCountedSet *set1 = [NSCountedSet setWithArray:array1];
NSCountedSet *set2 = [NSCountedSet setWithArray:array2];
return [set1 isEqualToSet:set2];
}
NSCountedSet
is a collection of different objects, where each object has an associated counter with it. Therefore the result for
NSArray *array1 = @[@0,@1,@2,@3];
NSArray *array2 = @[@2,@3,@1,@0];
is YES
, but for
NSArray *array1 = @[@1,@1,@3,@3];
NSArray *array2 = @[@3,@3,@3,@1];
the result is NO
.
更新:如果数组有重复元素,这将不起作用!
NSSet
您可以使用这些数组创建两个s 并进行比较。
NSArray * array1 = @[@0,@1,@2,@3];
NSArray * array2 = @[@2,@3,@1,@0];
NSSet *set1 = [NSSet setWithArray:array1];
NSSet *set2 = [NSSet setWithArray:array2];
NSLog(@"result %@", [set1 isEqualToSet:set2] ? @"YES" : @"NO");
if ([[NSSet setWithArray:array1] isEqualToSet:[NSSet setWithArray:array2]]) {
// the objects are the same
}
取元素总数。有一个柜台。并放置双'for循环'来解析彼此的每个元素。在每次匹配时增加计数器。注意:这在所有元素都是唯一的情况下有效。
如果不同或您不知道,请将它们排序并一对一匹配。
另一种方法是使用NSHashTable
.
- (BOOL)array:(NSArray *)array1 containsTheSameObjectsAsArray:(NSArray *)array2 {
if (array1.count != array2.count) {
return NO;
}
NSHashTable *table = [[NSHashTable alloc] initWithOptions:NSHashTableWeakMemory
capacity:array1.count];
for (NSObject *object in array1) {
[table addObject:object];
}
for (NSObject *object in array2) {
if (![table containsObject:object]) {
return NO;
}
}
return YES;
}
Note that NSHashTable
requires iOS 6+