二维数组转一维数组:
NSArray *array = @[
@[@"11", @"12"],
@[@"21", @"22"],
@[@"31", @"32"],
@[@"41", @"42"],
@[@"51", @"52"]];
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);
结果如下:
(
11,
21,
31,
41,
51,
12,
22,
32,
42,
52
)
当把上面代码下方替换 就改变了排序位置
NSInteger count = tmpArray.count;
for (NSInteger i=0; i<secArray.count; i++) {
secArray[i] = array[i/count][i%count];
}
改变结果如下:
(
11,
12,
21,
22,
31,
32,
41,
42,
51,
52
)
二维数组倒置:
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);
结果如下:
(
(
11,
21,
31,
41,
51
),
(
12,
22,
32,
42,
52
)
)
一维数组转二维数组(5*2的二维数组)
NSArray *secArray = @[
@"11", @"12",
@"21", @"22",
@"31", @"32",
@"41", @"42",
@"51", @"52"
];
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);
// 5*2;
// m = X / 2;
// n = X % 2; m、n 代表数组下标
打印结果如下:
(
(
11,
12
),
(
21,
22
),
(
31,
32
),
(
41,
42
),
(
51,
52
)
)