简体   繁体   中英

indexesOfObjectsPassingTest: | once indexes have been found how to check if if they are sequential?

I am using indexesOfObjectsPassingTest successfully to get the indexes that I require.

With the found indexes I would like check if any of the indexes are sequential. If they are I would like to get the first in that sequence and the last in the sequence.

        NSMutableArray *domesticSetResult = [[NSMutableArray alloc]init];
        domesticSetResult = nil;

        NSMutableArray *matches = [NSMutableArray array];

        NSIndexSet *domesticIndex = [self.days indexesOfObjectsPassingTest: ^(id obj, NSUInteger idx, BOOL *stop)
                              {
                                  if ([obj isDomestic])
                                      return YES; // found a match, keep going
                                  else
                                      return NO; // keep looking
                              } ];

        [domesticIndex enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
            [matches addObject:[self.days objectAtIndex:idx]];
        }];
        NSLog(@"\n\nDomestic indexes: %@\n\n", domesticIndex);

As an example the log produces

Domestic indexes: [number of indexes: 3 (in 2 ranges), indexes: (0 3-8)]

With index 0 there is only 1 in sequence so I would like it returned. With index 3-8 I would like to return 3 and 8

I can enumerate the indexes but an not sure how to check that the indexes are in sequence and to just get the indexes that are at the beginning and end of each sequence.

Let NSIndexSet do the work for you.

For simplicity, this code constructs a second index set from the first, but it's easily adapted to do whatever you want.

NSMutableIndexSet *s = [NSMutableIndexSet indexSetWithIndex:0];
[s addIndex:3];
[s addIndex:4];
[s addIndex:5];
[s addIndex:6];
[s addIndex:7];
[s addIndex:8];

NSMutableIndexSet *s2 = [[NSMutableIndexSet alloc] init];
[s enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
  NSLog(@"%@", NSStringFromRange(range));

  [s2 addIndex:range.location];
  if (range.length > 1) {
    [s2 addIndex:range.location + range.length - 1];
  }
}];

NSLog(@"%@", s2);

The log at the end will print the 3 indexes: 0, 3, 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM