I've an array with 1 to 16 numbers self.gridArray = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16", nil];
I am using this function to randomize or shuffle the array items
-(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);
}
This function is working perfectly. My question is that suppose it gives me the shuffled array as (9,15,3,5,1,6,7,8,14,13,12,2,16,10,4,11)
which I have placed it in a 4x4
grid. Now I want to find the adjacent numbers for lets say 7
they will be 6,3,8,12
. How to find them?
Another example if I want to find adjacent numbers of 11
they will be 2,4
.
Try this:
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