Objective C 中的棋盘矩阵

Checkerboard Matrix in Objective C

如何在 objective c 中生成 n 行和长度的棋盘矩阵? (使用 NSLOG 打印如下所示的输出)

示例:

输入 n = 5

输出为

         [1 0 1 0 1
          0 1 0 1 0
          1 0 1 0 1
          0 1 0 1 0 
          1 0 1 0 1]

我在下面尝试了这个方法,它很接近。如有任何帮助,我们将不胜感激!

-(void)checkerboardOne:(int)length {   
    NSMutableArray *squares = [NSMutableArray arrayWithObjects: nil];
    for (int y = 1 ; y <= length; y++) { 
        if (y % 2) {
            for (int x = 0 ; x < length; x++) {
                if (x % 2 ) {  
                    [squares addObject:[NSString stringWithFormat:@"0"]];  
                } else {
                    [squares addObject:[NSString stringWithFormat:@"1"]];  
                }
            } //end row 0
        } else {
            for (int x = 0 ; x < length; x++) {
                if (x % 2 ) {
                    [squares addObject:[NSString stringWithFormat:@"1"]];
                } else {
                    [squares addObject:[NSString stringWithFormat:@"0"]];
                }
            } //end row 1
        }
        NSLog(@"==========\n%@", squares);
        [squares removeAllObjects];
    }
}

查看您的代码,您得到的输出似乎更像:

     [0 1 0 1 0
      1 0 1 0 1
      0 1 0 1 0 
      1 0 1 0 1
      0 1 0 1 0]

只需将外循环更改为:

for (int y = 0 ; y < length; y++) { 

获得想要的结果。

但是有一个更简单的方法:

- (void)checkerboardOne:(int)length {   
    NSMutableArray *squares = [NSMutableArray arrayWithCapacity:length * length];

    for (int r = 0; r < length; r++) {
        for (int c = 0; c < length; c++) {
            BOOL isEven = ((r + c) % 2) == 0;
            NSString *result = isEven ? @"1" : @"0";
            [squares addObject:result];
        }
    }

    NSLog(@"==========\n%@", squares);
}