How can I complete this Objective-C implementation of a cartesian product function?

给你一囗甜甜゛ 提交于 2019-12-05 06:26:00
NSArray *cartesianProductOfArrays(NSArray *arrays)
{
    int arraysCount = arrays.count;
    unsigned long resultSize = 1;
    for (NSArray *array in arrays)
        resultSize *= array.count;
    NSMutableArray *product = [NSMutableArray arrayWithCapacity:resultSize];
    for (unsigned long i = 0; i < resultSize; ++i) {
        NSMutableArray *cross = [NSMutableArray arrayWithCapacity:arraysCount];
        [product addObject:cross];
        unsigned long n = i;
        for (NSArray *array in arrays) {
            [cross addObject:[array objectAtIndex:n % array.count]];
            n /= array.count;
        }
    }
    return product;
}

NSArray NSMutableArray does not has next current reset functions. I think you can write a class to implement such function

@interface myArray {
    NSMutableArray* array;//the real array
    int index;//hole the index
}

-(id)current;
-(id)next;
-(id)reset;
@end

the 3 function will modify the index,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!