ios - How to get a unique selection from NSArray? -


this question has answer here:

i’ve written code select random color nsarray, how can make same color doesn’t selected 2 times in row? appreciated.

+ (nsarray *)colors {  static nsarray *colors = nil;  static dispatch_once_t once; dispatch_once(&once, ^{ colors = @[ //green [uicolor colorwithred:88.0/255.0 green:195.0/255.0 blue:98.0/255.0 alpha:1], //yellow [uicolor colorwithred:246.0/255.0 green:194.0/255.0 blue:48.0/255.0 alpha:1], //orange [uicolor colorwithred:236.0/255.0 green:135.0/255.0 blue:40.0/255.0 alpha:1], //red [uicolor colorwithred:226.0/255.0 green:51.0/255.0 blue:40.0/255.0 alpha:1], //blue [uicolor colorwithred:59.0/255.0 green:156.0/255.0 blue:218.0/255.0 alpha:1], //violet [uicolor colorwithred:138.0/255.0 green:70.0/255.0 blue:165.0/255.0 alpha:1], ]; });  return colours;  }  _selectedcolor = [colors objectatindex: arc4random() % [colors count]]; 

shuffle array of colors , return elements in order. when reach end, reshuffle , start over. make sure don't allow last element become first element avoid returning same element twice in row. guarantees use each color equal number of times.

@implementation uicolor (random)  static uicolor *rgb(cgfloat red, cgfloat green, cgfloat blue) {     return [uicolor colorwithred:red/255 green:green/255 blue:blue/255 alpha:1]; }  void shuffle(nsmutablearray *array) {     // based on http://stackoverflow.com/a/56656/77567     nsuinteger count = array.count;     if (count < 2) return;     // don't allow last element become first, don't same color twice in row.     [array exchangeobjectatindex:0 withobjectatindex:arc4random_uniform(count - 1)];     (nsuinteger = 1; < count - 1; ++i) {         nsinteger remainingcount = count - i;         nsinteger exchangeindex = + arc4random_uniform((u_int32_t )remainingcount);         [array exchangeobjectatindex:i withobjectatindex:exchangeindex];     } }  + (instancetype)randomcolor {      static dispatch_once_t once;     static nsmutablearray *colors;     static int nextcolorindex;     static dispatch_queue_t queue; // serializes access colors , nextcolorindex     dispatch_once(&once, ^{         colors = @[             rgb(88, 195, 98), // green             rgb(246, 194, 48), // yellow             rgb(236, 135, 40), // orange             rgb(226, 51, 40), // red             rgb(59, 156, 218), // blue             rgb(138, 70, 165), // violet         ].mutablecopy;         shuffle(colors);         queue = dispatch_queue_create("uicolor+random.randomcolor", 0);     });      __block uicolor *color;     dispatch_sync(queue, ^{         color = colors[nextcolorindex++];         if (nextcolorindex == colors.count) {             nextcolorindex = 0;             shuffle(colors);         }     });     return color; }  @end 

Comments