比较两个数组并找出变化

时间:2015-03-31 18:28:47

标签: ios objective-c matrix

我有一个包含3个数组的数组,比如名为_matrix的矩阵3x3 1 2 3 4 5 6 7 8 9 我有另一个名为_newMatrix的矩阵3x3 我需要一个函数来比较这两个矩阵,并给我改变的元素的索引,或者改变的东西。有没有直接的方法来解决我的问题?

2 个答案:

答案 0 :(得分:0)

以下是一个示例性方法。如果您需要帮助,请再次询问。但是如果你没有做出任何努力,你将不会得到更多的帮助。

- (NSArray*) getDifferencesBetween:(NSArray*)first and:(NSArray*)second {
  // create a NSMutableArray * as the return value      
  // get the dimension of the matrixes by first.count and first[0].count
  // iterate over the matrix in two nested for loops 
  // check if the value in first[x][y] differ from second[x][y]
  // if so, add the index (x + y * first.count) to the return value
  // return the return value (the NSMutableArray*)
}

答案 1 :(得分:0)

数组比较是一个有趣的问题。嵌套数组使这更有趣。

第一个也是最重要的问题是,您正在寻找什么样的输出。例如(为了简洁,我使用2x2矩阵),你想要一个代表差异的第三个矩阵吗?

[[2, 3],
 [4, 5]]

进行差异
[[3, 6],
 [5, 2]]

可能是:

[[1, 3],
 [2, -3]]

这似乎是一个合理的想法。让我们来看看我们如何实现这一点。

- (NSArray *)matrixByFindingDifferenceBetweenFirstMatrix:(NSArray *)firstMatrix secondMatrix:(NSArray *)secondMatrix {
    NSMutableArray *differenceMatrix = [[NSMutableArray alloc] init];
    for(int i = 0; i < firstMatrix.count; i++) {
        NSArray *row = [firstMatrix objectAtIndex:i];
        NSArray *secondMatrixRow = [secondMatrix objectAtIndex:i];
        NSMutableArray *differenceRow = [[NSMutableArray alloc] init];
        for(int j = 0; j < row.count; j++) {
            NSNumber *currentValue = [row objectAtIndex:j];
            NSNumber *newValue = [secondMatrixRow objectAtIndex:j];
            NSNumber *difference = @(newValue.intValue - currentValue.intValue);
            [differenceRow addObject:difference];
        }
        [differenceMatrix addObject:[NSArray arrayWithArray:differenceRow];
    }
    return [NSArray arrayWithArray:differenceMatrix];
}

这是有道理的。我不知道它是否是你想要的,但矩阵比较的核心在于嵌套迭代(显然是O(n ^ 2),所以避免使用非常大的矩阵)

编辑:只获取已更改元素的索引路径。

- (NSArray *)changedIndexPathsBetweenFirstMatrix:(NSArray *)firstMatrix secondMatrix:(NSArray *)secondMatrix {
    NSMutableArray *changedIndexes = [[NSMutableArray alloc] init];
    for(int i = 0; i < firstMatrix.count; i++) {
        NSArray *row = [firstMatrix objectAtIndex:i];
        NSArray *secondMatrixRow = [secondMatrix objectAtIndex:i];
        for(int j = 0; j < row.count; j++) {
            NSNumber *currentValue = [row objectAtIndex:j];
            NSNumber *newValue = [secondMatrixRow objectAtIndex:j];
            if(![currentValue isEqual:newValue]) {
                NSIndexPath *path = [NSIndexPath indexPathForRow:j inSection:j]; // Row is technically "column" in the sense of matrixes, and section is the matrix's row.
                [changedIndexes addObject:path];
            }
        }
        [differenceMatrix addObject:[NSArray arrayWithArray:differenceRow];
    }
    return [NSArray arrayWithArray:differenceMatrix];
}
相关问题