什么是洗牌NSMutableArray的最佳方式?

时间:2008-09-11 14:16:44

标签: objective-c cocoa shuffle

如果你有一个NSMutableArray,你如何随意洗牌?

(我有自己的答案,发布在下面,但我是Cocoa的新手,我很想知道是否有更好的方法。)


更新:正如@Mukesh所述,从iOS 10+和m​​acOS 10.12+开始,有一种-[NSMutableArray shuffledArray]方法可用于随机播放。有关详细信息,请参阅https://developer.apple.com/documentation/foundation/nsarray/1640855-shuffledarray?language=objc。 (但请注意,这会创建一个新数组,而不是将元素移动到位。)

12 个答案:

答案 0 :(得分:345)

我通过在NSMutableArray中添加一个类别来解决这个问题。

修改:感谢Ladd的回答,删除了不必要的方法。

修改:由于Gregory Goltsov的回答以及miho和blahdiblah的评论,将(arc4random() % nElements)更改为arc4random_uniform(nElements)

修改:循环改进,感谢Ron的评论

编辑:感谢Mahesh Agrawal发表评论,检查数组是否为空

//  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];
    if (count <= 1) return;
    for (NSUInteger i = 0; i < count - 1; ++i) {
        NSInteger remainingCount = count - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
        [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }
}

@end

答案 1 :(得分:74)

您不需要swapObjectAtIndex方法。 exchangeObjectAtIndex:withObjectAtIndex:已经存在。

答案 2 :(得分:38)

由于我还没有发表评论,我认为我会做出完整的回复。我以多种方式修改了Kristopher Johnson对我项目的实现(真的试图让它尽可能简洁),其中一个是arc4random_uniform(),因为它避免了modulo bias

// NSMutableArray+Shuffling.h
#import <Foundation/Foundation.h>

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

// NSMutableArray+Shuffling.m
#import "NSMutableArray+Shuffling.h"

@implementation NSMutableArray (Shuffling)

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

@end

答案 3 :(得分:9)

从iOS 10开始,您可以使用新的shuffled API:

https://developer.apple.com/reference/foundation/nsarray/1640855-shuffled

let shuffledArray = array.shuffled()

答案 4 :(得分:8)

略微改进和简洁的解决方案(与最佳答案相比)。

该算法是相同的,并在文献中描述为“Fisher-Yates shuffle”。

在Objective-C中:

@implementation NSMutableArray (Shuffle)
// Fisher-Yates shuffle
- (void)shuffle
{
    for (NSUInteger i = self.count; i > 1; i--)
        [self exchangeObjectAtIndex:i - 1 withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
}
@end

在Swift 3.2和4.x中:

extension Array {
    /// Fisher-Yates shuffle
    mutating func shuffle() {
        for i in stride(from: count - 1, to: 0, by: -1) {
            swapAt(i, Int(arc4random_uniform(UInt32(i + 1))))
        }
    }
}

在Swift 3.0和3.1中:

extension Array {
    /// Fisher-Yates shuffle
    mutating func shuffle() {
        for i in stride(from: count - 1, to: 0, by: -1) {
            let j = Int(arc4random_uniform(UInt32(i + 1)))
            (self[i], self[j]) = (self[j], self[i])
        }
    }
}

注意:A more concise solution in Swift is possible from iOS10 using GameplayKit.

注意:An algorithm for unstable shuffling (with all positions forced to change if count > 1) is also available

答案 5 :(得分:6)

这是改组NSArrays或NSMutableArrays的最简单,最快捷的方法 (对象拼图是一个NSMutableArray,它包含拼图对象。我已添加到 拼图对象变量索引,表示数组中的初始位置)

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++;
    }
}

日志输出:

 #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

您也可以将obj1与obj2进行比较,然后决定要返回的内容 可能的值是:

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

答案 6 :(得分:2)

有一个很好的流行图书馆,它有这个方法,称为SSToolKit in GitHub。 文件NSMutableArray + SSToolkitAdditions.h包含shuffle方法。你也可以使用它。其中,似乎有很多有用的东西。

此库的主页是here

如果您使用此代码,您的代码将如下所示:

#import <SSCategories.h>
NSMutableArray *tableData = [NSMutableArray arrayWithArray:[temp shuffledArray]];

这个库也有一个Pod(参见CocoaPods)

答案 7 :(得分:2)

从iOS 10开始,您可以使用NSArray shuffled() from GameplayKit。这是Swift 3中Array的帮助器:

import GameplayKit

extension Array {
    @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
    func shuffled() -> [Element] {
        return (self as NSArray).shuffled() as! [Element]
    }
    @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
    mutating func shuffle() {
        replaceSubrange(0..<count, with: shuffled())
    }
}

答案 8 :(得分:1)

如果元素有重复。

e.g。阵列:A A A B B或B B A A A

唯一的解决方案是:A B A B A

sequenceSelected是一个NSMutableArray,它存储类obj的元素,它们是指向某个序列的指针。

- (void)shuffleSequenceSelected {
    [sequenceSelected shuffle];
    [self shuffleSequenceSelectedLoop];
}

- (void)shuffleSequenceSelectedLoop {
    NSUInteger count = sequenceSelected.count;
    for (NSUInteger i = 1; i < count-1; i++) {
        // Select a random element between i and end of array to swap with.
        NSInteger nElements = count - i;
        NSInteger n;
        if (i < count-2) { // i is between second  and second last element
            obj *A = [sequenceSelected objectAtIndex:i-1];
            obj *B = [sequenceSelected objectAtIndex:i];
            if (A == B) { // shuffle if current & previous same
                do {
                    n = arc4random_uniform(nElements) + i;
                    B = [sequenceSelected objectAtIndex:n];
                } while (A == B);
                [sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:n];
            }
        } else if (i == count-2) { // second last value to be shuffled with last value
            obj *A = [sequenceSelected objectAtIndex:i-1];// previous value
            obj *B = [sequenceSelected objectAtIndex:i]; // second last value
            obj *C = [sequenceSelected lastObject]; // last value
            if (A == B && B == C) {
                //reshufle
                sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];
                [self shuffleSequenceSelectedLoop];
                return;
            }
            if (A == B) {
                if (B != C) {
                    [sequenceSelected exchangeObjectAtIndex:i withObjectAtIndex:count-1];
                } else {
                    // reshuffle
                    sequenceSelected = [[[sequenceSelected reverseObjectEnumerator] allObjects] mutableCopy];
                    [self shuffleSequenceSelectedLoop];
                    return;
                }
            }
        }
    }
}

答案 9 :(得分:-1)

NSUInteger randomIndex = arc4random() % [theArray count];

答案 10 :(得分:-1)

Kristopher Johnson's answer非常好,但并非完全随机。

给定一个包含2个元素的数组,此函数始终返回反转数组,因为您在其余索引上生成随机范围。更准确的shuffle()函数就像

- (void)shuffle
{
   NSUInteger count = [self count];
   for (NSUInteger i = 0; i < count; ++i) {
       NSInteger exchangeIndex = arc4random_uniform(count);
       if (i != exchangeIndex) {
            [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
       }
   }
}

答案 11 :(得分:-2)

修改:这不正确。出于参考目的,我没有删除此帖子。请参阅有关此方法不正确的原因的评论。

这里的简单代码:

- (NSArray *)shuffledArray:(NSArray *)array
{
    return [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if (arc4random() % 2) {
            return NSOrderedAscending;
        } else {
            return NSOrderedDescending;
        }
    }];
}