1

我有两个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];
      }

    }
  }
}
4

2 回答 2

0
  1. 合并两个数组。
  2. 按文本 ASC、频率 DESC 对结果数组进行排序
  3. 循环遍历数组
    a。查看数组中的下一项。如果文本与当前单词相同,则将其从数组中删除。如果不同,继续循环。

    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
    }
    
于 2013-06-07T13:36:37.913 回答
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]; 
       }
   }
 }
于 2013-06-09T18:08:39.190 回答