Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Split an array into two separate arrays based on even/odd indexes

I have an array, NSMutableArray *stringArray that looks like this

stringArray = 

[0]String1
[1]String2
[2]String3
[3]String4
[4]String5
[5]String6

How would I go about splitting this array into two arrays based on even/odd indexes?

Example:

NSMutableArray *oddArray = ([1], [3], [5]);

NSMutableArray *evenArray = ([0], [2], [4]);

Thanks in advance!

like image 714
hmzfier Avatar asked Feb 14 '26 15:02

hmzfier


2 Answers

create two mutable arrays, use enumerateObjectsWithBlock: on the source array and check idx % 2 to put it into first or second array

Using the ternary operator:

NSArray *array = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12];
NSMutableArray *even = [@[] mutableCopy];
NSMutableArray *odd = [@[] mutableCopy];
[array enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
    NSMutableArray *evenOrOdd = (idx % 2) ? even : odd;
    [evenOrOdd addObject:object];
}];

If you like super compact code you could use the ternary operator like

[((idx % 2) ? even : odd) addObject:object];

If you want to split the array to N arrays, you can do

NSArray *array = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12];

NSArray *resultArrays = @[[@[] mutableCopy],
                          [@[] mutableCopy],
                          [@[] mutableCopy]];

[array enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
        [resultArrays[idx % resultArrays.count] addObject:object];
}];

In Objective-C Categories should come to your mind to create re-uasable code:

@interface NSArray (SplittingInto)
-(NSArray *)arraysBySplittingInto:(NSUInteger)N;
@end

@implementation NSArray (SplittingInto)
-(NSArray *)arraysBySplittingInto:(NSUInteger)N
{
    NSAssert(N > 0, @"N cant be less than 1");
    NSMutableArray *resultArrays = [@[] mutableCopy];
    for (NSUInteger i =0 ; i<N; ++i) {
        [resultArrays addObject:[@[] mutableCopy]];
    }

    [self enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
                                [resultArrays[idx% resultArrays.count] addObject:object];
                            }];
    return resultArrays;
}
@end

Now you can do

NSArray *array = [@[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12] arraysBySplittingInto:2];

array contains

(
        (
        1,
        3,
        5,
        7,
        9,
        11
    ),
        (
        2,
        4,
        6,
        8,
        10,
        12
    )
)
like image 60
vikingosegundo Avatar answered Feb 17 '26 04:02

vikingosegundo


Create two NSIndexSets, one for the even indexes and one for the odd, then use objectsAtIndexes: to extract the corresponding slices of the array.

like image 29
rickster Avatar answered Feb 17 '26 05:02

rickster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!