适用于商品选择 统计商品规格计价 移动端上架商品使用 多维数组排列
#import "ViewController.h"
#import "NSDictionary+Log.h"
@interface ViewController ()
@property (nonatomic, strong) NSMutableArray *firstArray;//数组1
@property (nonatomic, strong) NSMutableArray *secondArray;//数组2
@property (nonatomic, strong) NSMutableArray *thirdArray;//数组3
@property (nonatomic, strong) NSMutableArray *fourthArray;//数组4
@property (nonatomic, strong) NSMutableArray *combinationArray;//最终组合数组
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.combinationArray = [[NSMutableArray alloc] init];
//创建数据
self.firstArray = [NSMutableArray arrayWithObjects:@"1-大棚种植",@"1-农民种植",@"1-全国调货", nil];
self.secondArray = [NSMutableArray arrayWithObjects:@"2-黄瓜",@"2-萝卜",@"2-南瓜", nil];
self.thirdArray = [NSMutableArray arrayWithObjects:@"3-1斤",@"3-5斤",@"3-10斤", nil];
self.fourthArray = [NSMutableArray arrayWithObjects:@"4-新鲜",@"4-冰冻", nil];
NSMutableArray * allArray = [[NSMutableArray alloc]initWithObjects:self.firstArray,self.secondArray,self.thirdArray,self.fourthArray, nil];
NSMutableArray * addArray = [[NSMutableArray alloc] init];
[self getCombination:0 allArray:allArray addArray:addArray];
}
#pragma mark - 获取多维数组组合
- (void)getCombination:(NSInteger)kid allArray:(NSMutableArray *)allArray addArray:(NSMutableArray *)addArray
{
if (kid < allArray.count) {
NSMutableArray * dataArr = [allArray objectAtIndex:kid];
if (dataArr.count == 0) {
return;
}
for (int i = 0; i < dataArr.count; i ++) {
NSMutableArray * newArr = [NSMutableArray new];
newArr = [addArray mutableCopy];
[newArr addObject:dataArr[i]];
[self getCombination:kid+1 allArray:allArray addArray:newArr];
}
}else
{
NSMutableArray * dataArr = [NSMutableArray new];
for (int i = 0; i < addArray.count; i ++ ) {
[dataArr addObject:addArray[i]];
}
[self.combinationArray addObject:dataArr];
NSLog(@"组合--->%@,组合数量-->%lu",self.combinationArray,(unsigned long)self.combinationArray.count);
}
}
@end
运行示例:(因为数据量过大 截取部分长度打印 排列组合数组)
2021-08-25 22:25:12.497785+0800 TESTDemo[4128:203290] 组合--->[
[
1-大棚种植,
2-黄瓜,
3-1斤,
4-新鲜
],
[
1-大棚种植,
2-黄瓜,
3-1斤,
4-冰冻
],
、、、、、、、、、、、、、
[
1-大棚种植,
2-南瓜,
3-10斤,
4-冰冻
],
[
1-农民种植,
2-黄瓜,
3-1斤,
4-新鲜
]
网友评论