简体   繁体   English

检查NSArray中每对唯一的对象

[英]Check against every unique pair of objects in an NSArray

I have an array of numbers. 我有一个数字数组。 I need to compare every number in the array with every other number in the array without any duplication of comparison sets. 我需要将数组中的每个数字与数组中的每个其他数字进行比较,而无需重复比较集。 Example, need to compare objects at index 0 and 1 but don't want to double up later by checking objects at index 1 and 0. 例如,需要比较索引0和1的对象,但不希望以后通过检查索引1和0的对象来加倍。

Can anyone help me out with the algorithm for this. 谁能帮我解决这个问题。 It would be greatly appreciated. 这将不胜感激。

I don't know what you need to do this for as there are probably better ways to accomplish whatever you are trying to do, but for the case you are talking about, you could do a simple: 我不知道您需要做什么,因为可能有更好的方法来完成您想做的事情,但是对于您正在谈论的情况,您可以做一个简单的事情:

for (int n=0;n<[array count];n++) {
    for (int m=n+1;m<[array count];m++) {
        //check your array based on objects at index n and m;
    }
}

This just loops through the array from beginning to end, and for each object loops through every object after it and you can compare them or do whatever. 这只是从头到尾循环遍历数组,对于每个对象,循环遍历数组之后的每个对象,您可以比较它们或执行任何操作。 Starting the inner loop at n+1 instead of 0 prevents you from repeating comparisons. n+1而不是0开始内部循环可防止您重复比较。

Use an NSMutableOrderedSet if it helps solve your problem. 如果可以帮助解决您的问题,请使用NSMutableOrderedSet。 Or another mutable array and add objects from your original array to it one by one using containsObject: to test if the object youre about to insert will be a duplicate. 或另一个可变数组,并使用containsObject:将原始数组中的对象一个个地添加到其中,以测试您要插入的对象是否是重复对象。

You can iterate over the array and at each number compare it with the next numbers in the array only. 您可以遍历数组,并在每个数字处将其仅与数组中的下一个数字进行比较。 if you have array with size 5, then at arr[2] compare it with arr[3], arr[4] only. 如果数组大小为5,则在arr [2]处将其与arr [3],arr [4]进行比较。

psudo code: 伪代码:

NSArray *arr;
for(int i = 0; i < arr.count ; i++)
{
  NSNumber *num1 = [arr objectAtIndex:i];
  for(int j = i + 1; j < arr.count; j++)
     {
       NSNumber *num2 = [arr objectAtIndex:j];
       //compare here num1 with num2
     }
 }

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

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