NSArray *arr = [NSArray arrayWithObjects:@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, nil];
NSUInteger numOfTeam = 0;
//计算分组个数
if ([arr count] % 3 == 0) {
numOfTeam = [arr count] / 3;
} else {
numOfTeam = [arr count] / 3 + 1;
}
//定义可变字典
NSMutableDictionary *dic = nil;
//定义可变数组
NSMutableArray *manageArr = [NSMutableArray arrayWithCapacity:numOfTeam];
//定义无符号整数集合
NSIndexSet *indexSet = nil;
//把每组的元素放在manageArr中
for (NSUInteger i = 0; i < numOfTeam; i++) {
if (i == [arr count] / 3) {
//若分配到最后一组,则为最后一组分配[arr count] % 3的length
indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(i * 3, [arr count] % 3)];
} else {
若不到最后一组,则分配3的length
indexSet = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(i * 3, 3)];
}
//将3个元素放在temp数组中
NSArray *temp = [NSArray arrayWithArray:[arr objectsAtIndexes:indexSet]];
//制作字典dic的key为str
NSString *str = [NSString stringWithFormat:@"%lu", i];
dic = [NSMutableDictionary dictionaryWithObject:temp forKey:str];
[manageArr addObject:[dic objectForKey:str]];
}
NSLog(@"manageArr:%@", manageArr);
有一个数组,数组中有13个元素,先将该数组进行分组,每3个元素为一组,分为若干组,最后用一个数组统一管理这些分组.(要动态创建数组)
最新推荐文章于 2021-03-06 15:05:45 发布