在objective-c中混洗一个数组 [英] Shuffling an array in objective-c

查看:118
本文介绍了在objective-c中混洗一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

什么是洗牌NSMutableArray的最好方法?

我为iphone / iPad开发应用程序。我想要对存储在NSArray中的对象进行随机播放。有没有办法用objective-c实现它?

I develop apps for iphone/iPad.I want to shuffle the objects stored in an NSArray.Is there any way to achieve it with objective-c?

推荐答案

向NSMutableArray添加一个类别,代码由Kristopher Johnson提供 -

Add a category to NSMutableArray, with code provided by Kristopher Johnson -

//  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
{

  static BOOL seeded = NO;
  if(!seeded)
  {
    seeded = YES;
    srandom(time(NULL));
  }

    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

这篇关于在objective-c中混洗一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆