从自定义对象的NSArray中删除重复项也会比较和编辑它们

时间:2013-06-07 11:44:54

标签: iphone ios objective-c cocoa-touch nsmutablearray

我有两个NSMutableArrays。每个都包含一个自定义单词对象。自定义单词有2个属性文本和频率。现在我想以这样的方式组合这两个arrays,如果这两个数组中有相同的文本,那么它应该比较这两个文本的频率并选择两者中的最高频率。而且它应该删除array中的重复项。 我为此尝试了所有逻辑,但无法做到这一点。任何人都可以帮助我解决这个问题。遵循代码。但它也应删除重复项。

for (int i = 0; i < [array count]; i++) {
  for (int j = 0; j < [array count]; j++)  {
    if ([[[array objectAtIndex:i]firstWord] isEqualToString:[[array objectAtIndex:j] firstWord]]) {

      if ([[array objectAtIndex:i] frequency] < [[array objectAtIndex:j] frequency]) {
        CustomWordFrequency *word = [array objectAtIndex:i];
        word.frequency = [[array objectAtIndex:j] frequency];
        [array replaceObjectAtIndex:i withObject:word];
      }

    }
  }
}

2 个答案:

答案 0 :(得分:0)

  1. 合并两个阵列。
  2. 按文本ASC,频率DESC
  3. 对结果数组进行排序
  4. 循环通过阵列
    一个。查看数组中的下一个项目。如果文本与当前单词相同,请将其从数组中删除。如果不同,请继续循环。

    NSArray *combined = [firstArray arrayByAddingObjectsFromArray:secondArray];
    [combined sortUsingComparator:^(id firstObject, id secondObject) {
      NSComparisonResult *result = [firstObject.text compare:secondObject.text];
      if (result == NSOrderedAscending) return NSOrderedAscending;
      if (result == NSOrderedDescending) return NSOrderedDescending;
      if (result == NSOrderedSame) {
        result = [firstObject.frequency compare:secondObject.frequency];
        if (result == NSOrderedAscending) return NSOrderedDescending;
        if (result == NSOrderedDescending) return NSOrderedAscending;
        if (result == NSOrderedSame) return NSOrderedSame;
      }
    }];
    for (int i = 0; i < [combined count] - 2; ++i) {
       CustomWordFrequency *word = [combined objectAtIndex:i];
       int j = i + 1;
       while ([word.text compare:[combined objectAtIndex:j].text == NSOrderedSame) {
         [combined removeObjectAtIndex:j];
         j++;
         if (j == [combined count]) {break;}
       }
       if (i >= [combined count] - 2) {break;} // the count keeps changing so check here
    }
    

答案 1 :(得分:0)

NSMutableArray *combinedArray = [[NSMutableArray alloc] init];
BOOL flagForMatchFound = FALSE;
for(CustomWordFrequency *firstWord in firstArray)
 {
   flagForMatchFound = FALSE;
   for(CustomWordFrequency *secondWord in secondArray)
   {
       if([firstWord.firstWord isEqualToString:secondWord.firstWord])
       {
          if(firstWord.frequency >= secondWord.frequency)
          {
               [combinedArray addObject:firstWord];
               flagForMatchFound = TRUE;
          }
          else
               [combinedArray addObject:secondWord];
       }
       else
       {
          if(!flagForMatchFound)
              [combinedArray addObject:secondWord]; 
       }
   }
 }