根据另一个数组中的值选择的 NSArray 中 NSDates 的累积 NSTimeInterval

Cumulative NSTimeInterval of NSDates in an NSArray selected based on values in another array

我有两个数组,一个是 NSNumber;另一个有 NSDates。我希望遍历数字数组,对于符合特定标准的每个数字——比方说 "is greater than 5"——我将保存该索引。然后遍历日期数组我想获取那些相同的索引。

然后我想找到每组日期的第一个和最后一个之间的NSTimeInterval,然后对这些间隔求和

举个例子:

NSArray *doubleArray = @[@3, @5, @6, @6, @7, @2, @8, @9, @2, @10];
NSArray *dateArray = @[dateA, dateB, dateC, dateD, dateE, dateF, dateG, dateH, dateI, dateJ];

doubleArray 中的每个对象都超过 5 的情况下,我希望对象在 dateArray 中具有相同的索引。所以范围是 2-4、6-7 和 10。 我如何找到范围开始和结束日期之间的时间间隔,然后将它们加在一起以获得累计总和?对于单个项目,我可能只是为其设置一个默认间隔时间。在这个例子中,我想要 [dateC timeIntervalSinceDate:dateE] + [dateG timeIntervalSinceDate:dateH] + defaultInterval

这个问题的第一部分,获取第二个数组中与第一个数组中满足特定条件的对象相对应的日期,非常简单。使用 indexesOfObjectsPassingTest:

从第一个数组中获取 NSIndexSet
NSIndexSet * indexes = [doubles indexesOfObjectsPassingTest:^(NSNumber * num, NSUInteger idx, BOOL *stop){
                            return (BOOL)([num doubleValue] > 5);
                        }];

从那里,您可以用日期创建一个新数组:

NSArray * selectedDates = [dates objectsAtIndexes:indexes];

如果你想添加每一对选定的日期,这是一个简单的成对迭代:

NSTimeInterval cumInterval = 0;
NSUInteger count = [selectedDates count];
for( NSUInteger i = 0; i < count - 1 /* stop before last object */; i++ ){
    NSDate * firstDate = selectedDates[i];
    NSDate * secondDate = selectedDates[i+1];
    cumInterval += [firstDate timeIntervalSinceDate:secondDate];
}

另一方面,如果您只想添加每个分组的第一个和最后一个(即样本中从日期 B 到 E 的间隔和从 G 到 H 的间隔),则可以枚举NSIndexSet,它实际上将索引存储为范围。

NSTimeInterval defaultInterval = ...;
NSTimeInterval __block cumInterval = 0;
[indexes enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
    if( range.length == 1 ){
        cumInterval += defaultInterval;
        return;
    }

    NSUInteger firstIdx = range.location;
    NSUInteger secondIdx = range.location + range.length - 1;
    NSDate * firstDate = dates[firstIdx];
    NSDate * secondDate = dates[secondIdx];

    cumInterval += [firstDate timeIntervalSinceDate:secondDate];
}];