Joe Habadas
Joe Habadas

Reputation: 628

Simplifying loop in Objective-C

I have this enormous loop in my code (not by choice), because I can't seem to make it work any other way. If there's some way make this simple as opposed to me repeating it +20 times that would be great, thanks.

for (NSUInteger i = 0; i < 20; i++) {
     if (a[0] == 0xFF || b[i] == a[0]) {
         c[0] = b[i];
         if (d[0] == 0xFF) {
             d[0] = c[0];
         }

         ... below repeats +18 more times with [i+2,3,4,etc] ...

         if (a[1] == 0xFF || b[i + 1] == a[1]) {
             c[1] = b[i + 1];
             if (d[1] == 0xFF) {
                 d[1] = c[1];
             }

           ... when it reaches the last one it calls a method ...

           [self doSomething];
           continue;
           i += 19;

          ... then } repeats +19 times (to close things)...
      }
   } 
}

I've tried almost every possible combo of things that I know of attempting to make this smaller and efficient. Take a look at my flow chart — pretty huh? i'm not a madman, honest.

flowin' oldskool style

Upvotes: 0

Views: 140

Answers (2)

Vladimir
Vladimir

Reputation: 9743

If I haven't made a mistake:

for (NSUInteger i = 0; i < 20; i++) {
    BOOL canDoSomething = YES;

    for (NSUInteger j = 0; j < 20; j++) {
        if (a[j] == 0xFF || b[i+j] == a[j]) {
            c[j] = b[i+j];
            if (d[j] == 0xFF) {
                d[j] = c[j];
            }
        }
        else {
            canDoSomething = NO;
            break;
        }
    }

    if (canDoSomething) {
         [self doSomething];   
         break;     
         // according to your latest edit: continue; i+=19; 
         // continue does nothing as you use it, and i+=19 makes i >= 20
    }
} 

It's what your code does. But it looks like it will cause index out bounds exception. Perhaps nested loop's clause should look like

for (NSUInteger j = 0; i+j < 20; j++)

Upvotes: 3

Maciej Trybiło
Maciej Trybiło

Reputation: 1207

You want to use recursion.

Declare another method:

-(BOOL)doSthWithA:(int*)a B:(int*)b C:(int*)c D:(int*)d Integer:(int)j AnotherInteger:(int)i {

  // end of recursion 
  if(j == 20) {
    return YES;
  }

  if (a[j] == -0x1 || b[i+j] == a[j]) {
     c[j] = b[i+j];
     if (d[j] == -0x1) {
         d[j] = c[j];
     }
     return doSthWithA:a B:b C:c D:d Integer:j+1 AnotherInteger:i;
  }
  else return NO;
}

and in your code:

for (NSUInteger i = 0; i < 20; i++) {
  if(doSthWithA:a B:b C:c D:d Integer:0 AnotherInteger:i;) {
    [self doSomething];  
    i+=19;
  }
}

It probably can be all done better, but that translates your code into a more compact form.

Upvotes: 0

Related Questions