How can I efficiently select several unique random numbers from 1 to 50, excluding x?

后端 未结 5 427
囚心锁ツ
囚心锁ツ 2021-01-06 19:01

I have 2 numbers which are between 0 and 49. Let\'s call them x and y. Now I want to get a couple of other numbers which are not x or y, but are al

5条回答
  •  醉梦人生
    2021-01-06 19:15

    I'd do something more along the lines of:

    NSMutableSet * invalidNumbers = [NSMutableSet set];
    [invalidNumbers addObject:[NSNumber numberWithInt:x]];
    [invalidNumbers addObject:[NSNumber numberWithInt:y]];
    
    int nextRandom = -1;
    do {
      if (nextRandom >= 0) {
        [invalidNumbers addObject:[NSNumber numberWithInt:nextRandome]];
      }
      nextRandom = arc4random() % 49;
    } while ([invalidNumbers containsObject:[NSNumber numberWithInt:nextRandom]]);
    

提交回复
热议问题