求任意数组笛卡尔积 OC Swift 写法
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:@[@"1",@"2",@"3"]];
[arr addObject:@[@"4",@"5",@"6"]];
[arr addObject:@[@"7",@"8",@"9"]];
NSMutableArray *result = [NSMutableArray array];
[self Descartes:arr result:result layer:0 curstring:@""];
求这三个数组的笛卡尔积 ,结果应该是 有27个。
具体实现:
-(void)Descartes:(NSMutableArray <NSMutableArray <NSString *>*>*)dimvalue result:(NSMutableArray <NSString *>*)result layer:(NSInteger)layer curstring:(NSString *)curstring{
if (layer < (dimvalue.count - 1)) {
if (dimvalue[layer].count == 0) {
[self Descartes:dimvalue result:result layer:layer + 1 curstring:curstring];
}else{
for (int i = 0; i < dimvalue[layer].count; i++) {
[self Descartes:dimvalue result:result layer:layer + 1 curstring:[NSString stringWithFormat:@"%@%@",curstring,dimvalue[layer][i]]];
}
}
}else if (layer ==dimvalue.count - 1){
if (dimvalue[layer].count == 0) {
[result addObject:curstring];
}else{
for (int i = 0; i < dimvalue[layer].count; i++) {
NSString *string = [NSString stringWithFormat:@"%@%@",curstring,dimvalue[layer][i]];
[result addObject:string];
}
}
}
}
结果:
Swift:
var arr : [[String]] = [["1","2","3"],["4","5","6"],["7","8","9"]]
var result : [String] = []
func Descartes(inout dimvalue : [[String]],inout result : [String],layer : NSInteger ,curstring : String){
if layer < dimvalue.count - 1 {
if dimvalue[layer].count == 0 {
Descartes(&dimvalue, result: &result, layer: layer, curstring: curstring)
}else{
for (index, _) in dimvalue[layer].enumerate() {
Descartes(&dimvalue, result: &result, layer: layer + 1, curstring: curstring + dimvalue[layer][index])
}
}
}else if(layer == dimvalue.count - 1){
if dimvalue[layer].count == 0 {
result.append(curstring)
}else{
for (index, _) in dimvalue[layer].enumerate() {
result.append(curstring + dimvalue[layer][index])
}
}
}
}
Descartes(&arr, result: &result, layer: 0, curstring: "")
print(result)