0

我的代码中有这个巨大的循环(不是自愿的),因为我似乎无法让它以任何其他方式工作。如果有某种方法可以让这个简单,而不是我重复 +20 次,那就太好了,谢谢。

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)...
      }
   } 
}

我已经尝试了几乎所有我知道的试图使这个更小和更高效的组合。看看我的流程图——漂亮吧?我不是疯子,老实说。

流动的oldskool风格

4

2 回答 2

3

如果我没有记错:

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
    }
} 

这就是你的代码所做的。但看起来它会导致索引超出范围异常。也许嵌套循环的子句应该看起来像

for (NSUInteger j = 0; i+j < 20; j++)
于 2012-06-06T10:21:05.057 回答
0

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.

于 2012-06-06T10:31:12.187 回答