Finding out NSArray/NSMutableArray changes' indices

前端 未结 3 1413
陌清茗
陌清茗 2021-01-12 14:44

I have a NSMutableArray oldArray. Now, at one point, this NSMutableArray object gets updated with another NSMutableArray,

3条回答
  •  耶瑟儿~
    2021-01-12 15:16

    If both arrays are already sorted in ascending order, you can find the added and removed elements with a single loop over both arrays (using two independent pointers into the array):

    NSArray *oldArray = @[@"a",@"b",@"d",@"e",@"g"];
    NSArray *newArray = @[@"a",@"c",@"d",@"e",@"f",@"h"];
    
    NSMutableArray *removedArray = [NSMutableArray array];
    NSMutableArray *addedArray = [NSMutableArray array];
    
    NSUInteger iold = 0; // index into oldArray
    NSUInteger inew = 0; // index into newArray
    
    while (iold < [oldArray count] && inew < [newArray count]) {
        // Compare "current" element of old and new array:
        NSComparisonResult c = [oldArray[iold] compare:newArray[inew]];
        if (c == NSOrderedAscending) {
            // oldArray[iold] has been removed
            [removedArray addObject:@(iold)];
            iold++;
        } else if (c == NSOrderedDescending) {
            // newArray[inew] has been added
            [addedArray addObject:@(inew)];
            inew++;
        } else {
            // oldArray[iold] == newArray[inew]
            iold++, inew++;
        }
    }
    // Process remaining elements of old array:
    while (iold < [oldArray count]) {
        [removedArray addObject:@(iold)];
        iold++;
    }
    // Process remaining elements of new array:
    while (inew < [newArray count]) {
        [addedArray addObject:@(inew)];
        inew++;
    }
    
    NSLog(@"removed: %@", removedArray);
    NSLog(@"added: %@", addedArray);
    

    Output:

    removed: (
        1,
        4
    )
    added: (
        1,
        4,
        5
    )
    

提交回复
热议问题