两种快速打乱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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值