iOS 二维数组倒置及二维数组转一维数组

以这个5*2二维数组为列
NSArray *array = @[
                       @[@"11", @"12"],
                       @[@"21", @"22"],
                       @[@"31", @"32"],
                       @[@"41", @"42"],
                       @[@"51", @"52"]];

1.二维数组倒置(即变为2*5二维数组)

NSArray *tmpArray = array[0];
   NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:tmpArray.count];
   for (NSInteger i=0; i<tmpArray.count; i++) {
       NSMutableArray *lineArray = [NSMutableArray arrayWithCapacity:array.count];
       for (NSInteger j=0; j<array.count; j++) {
           [lineArray addObject:@"0"];
       [newArray addObject:lineArray];
   for (NSInteger i=0; i<array.count; i++) {
       for (NSInteger j=0; j<tmpArray.count; j++) {
           newArray[j][i] = array[i][j];
   NSLog(@"**********____%@", newArray);

打印结果如下:

2.二维数组转一维数组(即包含2*5个元素的一维数组)

NSArray *tmpArray = array[0];
    NSMutableArray *secArray = [NSMutableArray arrayWithCapacity:(tmpArray.count*array.count)];
    for (NSInteger i=0; i<(tmpArray.count*array.count); i++) {
        [secArray addObject:@"0"];
    NSInteger count = array.count;
    for (NSInteger i=0; i<secArray.count; i++) {
        secArray[i] = array[i%count][i/count];
    NSLog(@"**********----%@",secArray);

打印结果如下:

NSInteger count = tmpArray.count;
    for (NSInteger i=0; i<secArray.count; i++) {
        secArray[i] = array[i/count][i%count];
    NSLog(@"**********----%@",secArray);

打印结果如下:

// n = X % 2; m、n 代表数组下标 代码如下。。。紧接上面 NSMutableArray *transferArray = [NSMutableArray arrayWithCapacity:5]; for (NSInteger i=0; i<5; i++) { NSMutableArray *tmpArray = [NSMutableArray array]; for (NSInteger j=0; j<2; j++) { [tmpArray addObject:@"0"]; [transferArray addObject:tmpArray]; for (NSInteger i=0; i<secArray.count; i++) { transferArray[i/2][i%2] = secArray[i]; NSLog(@"**********----%@",transferArray);

打印结果如下