iphone - canonical way to randomize an NSArray in Objective C -
Is there a canonical way to randomize an array in Objective-C?
My feature library defines this class on NSMutableArray:
@interface NSMutableArray (ArchUtils_Shuffle) - (zero) shuffle; Without @ and // bias n selects a random integer below. // calculates M, a power above two, and random () takes modulo m, // then it throws a random number if it is between n and m // (more intuitive techniques, such as random () Take modulo n, a bias intro / toward smaller number in border.) Static NSUInteger random_below (NSUInteger N) {NSUInteger M = 1; // Less than two small power n // Perhaps this is a quick solution from the loop, but bit-twinning // is not my specialty {M & LT; & Lt; = 1; } While (M & L; n); NSUInteger Ret; Do {rate = random ()% m; } While (rate> n =); Return writ; } @ Implementation NSMutableArray (ArchUtils_Shuffle) - (zero) shuffle {// http://en.wikipedia.org/wiki/Knuth_shuffle (NSUntager i = [self calculation]; i> 1; i--) { NSUINDER G = Random_blo (i); [Self Exchange Object IndicEx: ObjectTime: I] with I-1; }} @end Ensure that you call random number generators (for example srandom (time (tap)) ); Otherwise the production will not be very random.
Comments
Post a Comment