-4

So, I was tasked with randomizing a multidimensional array in Objective-C.

I needed to make this:

[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

Look something like this:

[[4,8,6],[1,7,9],[2,11,10],[3,5,12]]

I did that by hand, so please excuse me for the poor randomization.

NYC Tech Engineer
  • 1,845
  • 2
  • 22
  • 23

1 Answers1

0

This is what I came up with, please feel free to critique or improve it. I borrowed certain parts from existing SO contributions.

-(NSMutableArray *)shuffleArray:(NSMutableArray *)array
{
    NSMutableArray *flatArray = [array valueForKeyPath:@"@unionOfArrays.self"];

    NSUInteger count = flatArray.count;

    for (NSUInteger i = 0; i < count; i++) {
        NSInteger remainingCount = count - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t)remainingCount);
        [flatArray exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }

    NSMutableArray *set = [[NSMutableArray alloc] init];
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];

    for (int i = 0; i < flatArray.count; i++) {
        [tempArray addObject:flatArray[i]];

        if ((i + 1) % 3 == 0) {
            [set addObject:[tempArray copy]];
            [tempArray removeAllObjects];
        }
    }

    return set;
}
Community
  • 1
  • 1
NYC Tech Engineer
  • 1,845
  • 2
  • 22
  • 23