[英]What is the best way to create a 10x10 grid and print it in the console?
I have something like this: 我有这样的事情:
NSMutableArray *theBoard = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
[theBoard addObject:[NSString stringWithFormat:@"o"]];
}
for (int i = 0; i < 10; i++)
{
NSLog(@" %@",[[theBoard subarrayWithRange:NSMakeRange(0+(i*10), 10)]componentsJoinedByString:@" "]);
}
Console output: 控制台输出:
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
o o o o o o o o o o
I need to work with the coordinates of the array . 我需要处理数组的坐标 。 How can I solve this problem? 我怎么解决这个问题?
What is the best way to create a 10x10 grid and print it in the console? 创建10x10网格并在控制台中打印它的最佳方法是什么?
Use a two dimensional array. 使用二维数组。
Here is how to do it: 这是操作方法:
NSArray *rowArray = @[@"o", @"o", @"o", @"o", @"o", @"o", @"o", @"o", @"o", @"o",];
NSMutableArray *board = [[NSMutableArray alloc] initWithCapacity:10];
for (int rowIndex = 0; rowIndex < 10; rowIndex ++)
{
[board addObject:[rowArray mutableCopy]];
}
Let's print the board to the console: 让我们将面板打印到控制台:
for (int rowIndex = 0; rowIndex < 10; rowIndex ++)
{
NSArray *row = board[rowIndex];
NSLog(@"|%@|", [row componentsJoinedByString:@" "]);
}
Now you can reference each field on the board with X,Y coordinates : 现在,您可以使用X,Y坐标引用板上的每个字段:
board[yourXLocation][yourYLocation];
Side note. 边注。 You can also declare your array in more visual way. 您还可以以更直观的方式声明数组。 To see what is going on. 看看发生了什么。
Example of an 3x3 array: 3x3数组的示例:
NSArray *myArray = [[NSMutableArray alloc] initWithArray:@[@[ @"o", @"o", @"o"],
@[ @"o", @"o", @"o"],
@[ @"o", @"o", @"o"]]];
You should use a multi-dimensional array, or in this case a 2d array. 您应该使用多维数组,在这种情况下应使用2D数组。 This will allow you to find elements using something like theBoard[0][0]
这将允许您使用诸如theBoard[0][0]
类的元素来查找元素
NSMutableArray *theBoard = [NSMutableArray array];
for (int i = 0; i < 10; i++) {
NSMutableArray *row = [NSMutableArray array];
for (int j = 0; j < 10; j++) {
[row addObject:[NSString stringWithFormat:@"o"]];
}
[theBoard addObject:row];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.