开发者

How to search an array cyclically?

开发者 https://www.devze.com 2023-03-07 23:52 出处:网络
This is more a curiosity question than a pressing one. This question is looking for a better way to do the following, meaning without using two for loops.

This is more a curiosity question than a pressing one. This question is looking for a better way to do the following, meaning without using two for loops.

I have an NSArray *array of NSStrings and a method -(BOOL)isGoodString:(NSString *)string. I want to jump into the array at a random 开发者_开发技巧spot and find the first good string, wrapping around the end if necessary. However, it may be that there is no good string, so I need to know that as well. Here's the current implementation:

-(NSString *)randomGoodString {
  int N = [array count]
  int start = arc4random() % N;
  for (int j=start; j<N ; ++j) {
    if isGoodString([array objectAtIndex:j]) {
      return [array objectAtIndex:j];
    }
  }
  for (j=0; j<start ; ++j) {
    if isGoodString([array objectAtIndex:j]) {
      return [array objectAtIndex:j];
    }
  }
  return @"";
}

Any suggestions? Efficiency would be nice, but since this really is more for curiosity, anything that works in finite time would be nice to hear about.


Eliminate your second search loop by using a modulus:

-(NSString *)randomGoodString {
  int N = [array count]
  int start = arc4random() % N;
  for (int j=0; j<N ; ++j) {
    index = (j+start)%N;
    if isGoodString([array objectAtIndex:index]) {
      return [array objectAtIndex:index];
    }
  }
  return @"";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消