【发布时间】:2015-03-31 18:28:46
【问题描述】:
我有一个由 3 个数组组成的数组,例如名为 _matrix 的矩阵 3x3 1 2 3 4 5 6 7 8 9 我有另一个名为 _newMatrix 的 3x3 矩阵 我需要一个函数来比较这两个矩阵并为我提供更改的元素或更改的内容的索引。有没有直接的方法可以解决我的问题?
【问题讨论】:
标签: ios objective-c matrix
我有一个由 3 个数组组成的数组,例如名为 _matrix 的矩阵 3x3 1 2 3 4 5 6 7 8 9 我有另一个名为 _newMatrix 的 3x3 矩阵 我需要一个函数来比较这两个矩阵并为我提供更改的元素或更改的内容的索引。有没有直接的方法可以解决我的问题?
【问题讨论】:
标签: ios objective-c matrix
数组比较是一个有趣的问题。嵌套数组使这变得更加有趣。
第一个也是最重要的问题是您要寻找什么样的输出。例如(为了简洁起见,我使用 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];
}
【讨论】:
下面是一个示例方法。如果您需要这方面的帮助,请再次询问。但是,如果您不付出任何努力,您将不会得到比这更多的帮助。
- (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*)
}
【讨论】: