1

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.

Chaudhry Talha
  • 7,231
  • 11
  • 67
  • 116

1 Answers1

2

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
Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17
  • the solution is working if it has 4 adjacent numbers. For example if the number are in a sequence `1,2,3,4....,15,16` in the `4x4` grid if you set `indexOfObject` to `1` it give an error on `if ( idx-4 >= 0 )` condition. – Chaudhry Talha Mar 15 '16 at 06:29
  • @TalhaCh I forgot that `idx` was a `NSUInteger`, and so when it goes "below 0", it underflows to a large positive integer. Ive edited the answer, try and see if it works. – Lincoln Cheng Mar 15 '16 at 06:39
  • this works just fine. But if you enter `13` as `indexOfObject` is shows 3 values `14,12,9` now `14,9` are valid but `12` is not as it is the last object of thrid row. If you have solution for that kindly edit your answer anyhow I got what i was looking for thank you for that. – Chaudhry Talha Mar 15 '16 at 07:23
  • 2
    @TalhaCh This should work now! Was too lazy to test out previously :P – Lincoln Cheng Mar 15 '16 at 07:37