2

I want to quickly create an array of numbers from 0 to 10000 but with stepping increments of 500, for an array that looks like this:

@[@0, @500, @1000, ... @10000]

in PHP, this is built in to the range function, you could generate it like this: range(0, 10000, 500)

I'm not really looking for answers like looping over some initial array or numerically over 0-10000 and using modulus or something, I just want to know if there's a built in function or common shorthand for doing this

Jamie Forrest
  • 10,895
  • 6
  • 51
  • 68
bruchowski
  • 5,043
  • 7
  • 30
  • 46

2 Answers2

3

There is no built-in function like that in Objective-C. As you hinted, the best way to do it is by looping as follows:

NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i <= 10000; i += 500) {
    [array addObject:@(i)];
}

If you want to make a method that works similarly to the PHP range function: Returns an array of elements from start to end, inclusive.

Do this:

+ (NSArray *)rangeWithStart:(NSInteger)start end:(NSInteger)end step:(NSInteger)step {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSInteger i = start; i <= end; i += step) {
        [array addObject:@(i)];
    }
    return [array copy];
}
Black Frog
  • 11,595
  • 1
  • 35
  • 66
Jamie Forrest
  • 10,895
  • 6
  • 51
  • 68
2

If you want to create a large array quickly, or one which is a range, then you can create an array which doesn't actually store all the values but computes them on the fly as needed.

To subclass NSArray you only need to implement two methods, count and objectAtIndex:, for your subclass to be a complete array.

Here is an implementation, so simple there are no comments ;-)

@interface RangeArray : NSArray

- (instancetype) initWithStart:(NSInteger)start end:(NSInteger)end step:(NSInteger)step;

@end

@implementation RangeArray
{
   NSInteger start, end, step;
   NSInteger count;
}

- (instancetype) initWithStart:(NSInteger)_start end:(NSInteger)_end step:(NSInteger)_step
{
   self = [super init];
   if (self)
   {
      start = _start;
      end = _end;
      step = _step;
      count = (end >= start && step > 0) || (end < start && step < 0) ? 1 + (end - start) / step : 0;
   }
   return self;
}

- (NSUInteger) count { return count; }

- (id) objectAtIndex:(NSUInteger)index { return @(start + step * index); }

@end

And you can generate your required range using:

RangeArray *range = [RangeArray.alloc initWithStart:0 end:10000 step:500];

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86