美文网首页
数组重新组合

数组重新组合

作者: 芳菲如故 | 来源:发表于2017-04-28 16:06 被阅读0次
NSDictionary *parameter = @{@"a":@[@"101", @"102"], @"b":@[@"203", @"206"], @"c":@[@"306"]};
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:parameter];
//调用
NSMutableArray *arr = [self CtArry:dic];

//实现方法
-(NSMutableArray * )CtArry:(NSMutableDictionary * _Nullable)myDict
{
    NSMutableArray * temp_arry = [[NSMutableArray alloc] init];
    // 先取字典kye排序,再插入到列表
    NSArray *myKeys = [myDict allKeys];
    NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    for(id key in sortedKeys) {
        id object = [myDict objectForKey:key];
        [temp_arry addObject:object];
    }
    
    NSMutableArray* result = [[NSMutableArray alloc] init];
    if ([temp_arry count] != 1) {
        // 重新组合所有可能性
        NSMutableArray *temp = [NSMutableArray arrayWithCapacity:[temp_arry count]];
        [self combine:result temp:temp Data:temp_arry Curr:0 Count:(int)[temp_arry count]];
        [temp removeAllObjects];
        temp = nil;
    }
    else
    {
        for (NSNumber * number in temp_arry[0]) {
            [result addObject:number];
        }
    }
    return result;
}

-(void) combine:(NSMutableArray*)result temp:(NSMutableArray *)temp_baseArray Data:(NSArray*) data Curr:(int) curr Count:(int) count
{
    if (curr == count)
    {
        [result addObject:[[NSMutableArray alloc] initWithArray:temp_baseArray]];
    }
    else
    {
        NSArray* array = [data objectAtIndex:curr];
        for (int i = 0; i < [array count]; ++i)
        {
            temp_baseArray[curr] = [array objectAtIndex:i];
            //             NSLog(@" \n%d\n%@ ",curr,temp_baseArray);
            [self combine:result temp:temp_baseArray Data:data Curr:curr+1 Count:count];
        }
    }
}

相关文章

网友评论

      本文标题:数组重新组合

      本文链接:https://www.haomeiwen.com/subject/toqazttx.html