两种快速打乱NSMutableArray的方法

1。利用交换

//  NSMutableArray_Shuffling.h

#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#else
#include <Cocoa/Cocoa.h>
#endif

// This category enhances NSMutableArray by providing
// methods to randomly shuffle the elements.
@interface NSMutableArray (Shuffling)
- (void)shuffle;
@end


//  NSMutableArray_Shuffling.m

#import "NSMutableArray_Shuffling.h"

@implementation NSMutableArray (Shuffling)

- (void)shuffle
{
   
NSUInteger count = [self count];
   
for (NSUInteger i = 0; i < count; ++i) {
       
// Select a random element between i and end of array to swap with.
       
int nElements = count - i;
       
int n = (random() % nElements) + i;
       
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
   
}
}

@end

2。利用排序
int randomSort(id obj1, id obj2, void *context ) {
       
// returns random number -1 0 1
   
return (random()%3 - 1);    
}

- (void)shuffle {
       
// call custom sort function
   
[puzzles sortUsingFunction:randomSort context:nil];

   
// show in log how is our array sorted
       
int i = 0;
   
for (Puzzle * puzzle in puzzles) {
       
NSLog(@" #%d has index %d", i, puzzle.index);
        i
++;
   
}
}

log output:

 #0 has index #6
 
#1 has index #3
 
#2 has index #9
 
#3 has index #15
 
#4 has index #8
 
#5 has index #0
 
#6 has index #1
 
#7 has index #4
 
#8 has index #7
 
#9 has index #12
 
#10 has index #14
 
#11 has index #16
 
#12 has index #17
 
#13 has index #10
 
#14 has index #11
 
#15 has index #13
 
#16 has index #5
 
#17 has index #2

you may as well compare obj1 with obj2 and decide what you want to return possible values are:

  • NSOrderedAscending = -1
  • NSOrderedSame = 0
  • NSOrderedDescending = 1

posted @ 2010-06-08 10:10  javawebsoa  Views(174)  Comments(0Edit  收藏  举报