在4x4网格中找到相邻框到一个框

时间:2016-03-14 10:10:28

标签: objective-c arrays nsmutablearray nsarray

我有一个包含1到16个数字self.gridArray = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16", nil];的数组 我正在使用此函数随机化或随机播放数组项

-(void)randomizeArray:(NSMutableArray *)myArray{
    NSUInteger count = [myArray count];

    for (NSUInteger i = 0; i < count; ++i)
    {
        unsigned long int nElements = count - i;
        unsigned long int n = (arc4random() % nElements) + i;
        [myArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }

    NSLog(@"%@",myArray);

}

此功能完美运行。我的问题是,假设它将洗牌后的数组作为(9,15,3,5,1,6,7,8,14,13,12,2,16,10,4,11)提供给我,我将其放在4x4网格中。现在我想找到相邻的数字,让我们说7它们将是6,3,8,12如何找到它们?
另一个例子,如果我想找到11的相邻数字,它们将是2,4

1 个答案:

答案 0 :(得分:2)

试试这个:

NSInteger idx = (NSInteger)[myArray indexOfObject:@"11"]; //obtain the index of the target number
NSMutableArray *adjacentNumbers = [[NSMutableArray alloc] init];

if ( idx+4 < 16 ) { [adjacentNumbers addObject:[myArray objectAtIndex:(NSUInteger)(idx+4)]]; } //number below
if ( idx+1 < 16 && (idx%4 != 3) ) { [adjacentNumbers addObject:[myArray objectAtIndex:(NSUInteger)(idx+1)]]; } //number on the right
if ( idx-4 >= 0 ) { [adjacentNumbers addObject:[myArray objectAtIndex:(NSUInteger)(idx-4)]]; } //number above
if ( idx-1 >= 0 && (idx%4 != 0) ) { [adjacentNumbers addObject:[myArray objectAtIndex:(NSUInteger)(idx-1)]]; } //number on the left