记录一次 不确定多层for循环的写法

原创
2016/10/14 14:25
阅读数 1.2K

最近做一个商城类型的项目,用到了选择规格,类似淘宝发布那个样式,需要多种规格组合,并且是多组数据组合,一时也比较麻烦,用for循环吧,也不确定是多少层,也麻烦,最后想到了递归,于是就写出来了下面的一段代码,也解决了这个问题。

- (void)cyle {
    _resultsArray = [NSMutableArray array];
    _dataArray = @[@[@"1",@"2",@"3"],
                   @[@"4",@"5",@"6",@"*"],
                   @[@"7",@"8",@"9"]];
    [self cyle:0 dataArr:_dataArray[0]];
    NSLog(@"%@",_resultsArray);
}
/*
 * @param count 循环层数
 * @param arr 每次循环数据数组
 */
- (void)cyle:(NSInteger)count dataArr:(NSArray *)arr {
    if (count == 0) {
        [_resultsArray addObjectsFromArray:arr];
    } else {
        NSMutableArray * tempArray = [NSMutableArray array];
        for (NSInteger i = 0; i < _resultsArray.count; i++) {
            for (NSInteger j = 0; j < arr.count; j++) {
                [tempArray addObject:[NSString stringWithFormat:@"%@-%@",_resultsArray[i],arr[j]]];
            }
        }
        [_resultsArray removeAllObjects];
        _resultsArray = tempArray;
    }
    count++;
    if (count >= _dataArray.count) {
        return;
    }
    [self cyle:count dataArr:_dataArray[count]];
}

/*
输出结果:
    "1-4-7",
    "1-4-8",
    "1-4-9",
    "1-5-7",
    "1-5-8",
    "1-5-9",
    "1-6-7",
    "1-6-8",
    "1-6-9",
    "1-*-7",
    "1-*-8",
    "1-*-9",
    "2-4-7",
    "2-4-8",
    "2-4-9",
    "2-5-7",
    "2-5-8",
    "2-5-9",
    "2-6-7",
    "2-6-8",
    "2-6-9",
    "2-*-7",
    "2-*-8",
    "2-*-9",
    "3-4-7",
    "3-4-8",
    "3-4-9",
    "3-5-7",
    "3-5-8",
    "3-5-9",
    "3-6-7",
    "3-6-8",
    "3-6-9",
    "3-*-7",
    "3-*-8",
    "3-*-9"
*/
展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部