我正在尝试构建一个包含 400 个整数的数组(在 20 x 20 矩阵的上下文中处理)。所有元素都初始化为 0,然后选择 40 个随机点具有整数 9(在扫雷上下文中指定为地雷)。由于某种原因,我的程序挂在了线上:
[map replaceObjectAtIndex: mine_placement withObject:[NSNumber numberWithInt:9]];
在此之后,我有一个例程来累积每个元素的地雷接近度,最后的位创建字符串对象以发送到控制台(日志)。我很想听 Objective-C 专业人士说我做错了什么,以及为什么输出不正确。它构建得很好,只是没有输出。我收到一些关于线程正在启动的消息。我是 Obj-C 的新手,所以对此事的任何想法都会很棒。
这是main里面的内容:
@autoreleasepool
{
int number_of_mines = 40;
int mine_placement;
// create map of 400 char elements
NSMutableArray* map = [[NSMutableArray alloc] init];
// char map[400];
// build array with zeros everywhere
for(int i = 0; i < 400; i++)
[map addObject:[NSNumber numberWithInt:0]];
// add randomly placed mines
for(int i = 0; i < number_of_mines; i++) // loop for 40 mines
{
mine_placement = arc4random() % 400;
while([map objectAtIndex: mine_placement] == [NSNumber numberWithInt:9]) // if we are already on a mine, repeat
{
mine_placement = arc4random() % 400;
}
[map replaceObjectAtIndex: mine_placement withObject:[NSNumber numberWithInt:9]];
}
// proximity accumulator (an iterative approach)
for(int i = 0; i < 400; i++)
{
if([map objectAtIndex: i] != [NSNumber numberWithInt:9])
{
int accumulator = 0;
// check top three neighbors
if(i >= 20) // past first row
{
if(i % 20 != 0) // past first column
if([map objectAtIndex: (i-21)] == [NSNumber numberWithInt:9]) // top-left
accumulator++;
if((i+1) % 20 != 0) // before last column
if([map objectAtIndex: (i-19)] == [NSNumber numberWithInt:9]) //top-right
accumulator++;
if([map objectAtIndex: (i-20)] == [NSNumber numberWithInt:9]) // top
accumulator++;
}
// check bottom three neighbors
if(i < 380) // before last row
{
if(i % 20 != 0) // past first column
if([map objectAtIndex: (i+19)] == [NSNumber numberWithInt:9]) // bottom-left
accumulator++;
if((i+1) % 20 != 0) // before last column
if([map objectAtIndex: (i+21)] == [NSNumber numberWithInt:9]) // bottom-right
accumulator++;
if([map objectAtIndex: (i+20)] == [NSNumber numberWithInt:9]) // bottom
accumulator++;
}
// left neighbor
if(i % 20 != 0) // past first column
if([map objectAtIndex: (i-1)] == [NSNumber numberWithInt:9]) // left
accumulator++;
// right neighbor
if((i+1) % 20 != 0) // before last column
if([map objectAtIndex: (i+1)] == [NSNumber numberWithInt:9]) // right
accumulator++;
if(accumulator > 0)
[[map objectAtIndex: i] replaceObjectAtIndex: i withObject:[NSNumber numberWithInt:accumulator]];
}
}
// output map of 400 char elements
// build string rows
NSMutableString* string_row = [[NSMutableString alloc] init];
for(int row = 0; row < 20; row++)
{
for(int s = 0; s < 20; s++)
{
[string_row insertString:[map objectAtIndex: s] atIndex:s];
}
NSLog(@"%@", string_row);
[string_row setString:@""]; // clear string_row for next row pass
}
}