获取n维数组中的下一个元素

时间:2015-07-07 01:14:57

标签: objective-c arrays algorithm multidimensional-array

我接受了一个我无法解决的面试问题。我觉得解决方案是递归的,但即便如此,我也无法对逻辑进行排序。问题如下

给定嵌套数组,编写一个枚举器类,使next()按顺序返回元素,例如:

所以如果输入是:[1,[4,3],6,[5,[1,0]]] 输出为:1,4,3,6,5,1,0

我应该在Objective-C中做到这一点,我的(糟糕的解决方案)是

- (void) getNext(NSArray *) array {

  while(!array.isEmpty)
    getNext(array objectAtIndex(first);
}

NSLog(@"object is %@", [array objectAtIndex[0]]);

有人有什么想法吗?我也会接受一个非客观的答案,只是为了看到逻辑

2 个答案:

答案 0 :(得分:1)

我创建了一个NSArray类别。

@interface NSArray(EXT)
@property (nonatomic, assign) NSNumber *index;
- (NSNumber *)next;
@end

static void *aIndex = &aIndex;
@implementation NSArray (EXT)
    - (NSNumber *)index {
    return objc_getAssociatedObject(self, aIndex);
}

- (void)setIndex:(NSNumber *)index {
    objc_setAssociatedObject(self, aIndex, index, OBJC_ASSOCIATION_ASSIGN);
}

- (NSNumber *)next {
    if(self.index.integerValue == self.count) {
        return nil;
    }
    else {
        id nextObj = [self objectAtIndex:self.index.integerValue];
        if([nextObj isKindOfClass:[NSNumber class]]) {
            self.index = @(self.index.integerValue+1);
            return nextObj;
        }
        else {
            id childNext = [(NSArray *)nextObj next];
            if(childNext == nil) {
                self.index = @(self.index.integerValue+1);
                return [self next];
            }
            else {
                return childNext;
            }
        }
    }
}
@end

你可以像下面这样使用它:

NSArray *input = @[@1, @[@4, @3], @6, @[@5, @[@1, @0]]];

NSNumber *next = [input next];
while (next != nil) {
    NSLog(@"%@", next);
    next = [input next];
}

答案 1 :(得分:0)

这个问题的简单解决方案是

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *finalArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *input = @[@1, @[@4, @3], @6, @[@5, @[@1, @0]]];
    _finalArray = [NSMutableArray array];

    [self arrayToString:input];

    NSLog(@"Final array %@", [self.finalArray componentsJoinedByString:@","]);
}


- (void)arrayToString: (NSArray *) array {
    for (int i = 0; i < [array count]; i++) {
        [self recurseValue:[array objectAtIndex:i]];
    }


}


- (void)recurseValue:(id)value {
    if ([value isKindOfClass:[NSNumber class]]) {
        [self.finalArray addObject:value];
    } else if ([value isKindOfClass:[NSArray class]]) {
        for (int i = 0; i< [value count]; i++) {
            [self recurseValue:[value objectAtIndex:i]];
        }
    }
}

输出:1,4,3,6,5,1,0