4

我有一个名为 putNumberUsed 的 NSMutableArray。它包含以下对象@"blah1,@"blah2",@"blah3",@"blah4"。我想随机打乱这些对象,例如,如果我选择:

 [putNumberUsed objectAtIndex:0] 

除了 "blah1" 之外,它会给我任何东西。我该怎么做呢?以下是我迄今为止使用的代码:

NSMutableArray *putNumbersUsed = [[NSMutableArray alloc] arrayWithObjects:@"blah1",@"blah2",@"blah3",@"blah4",nil];
4

6 回答 6

9

我认为,您可以为此编写一个循环。请检查以下代码,

for (int i = 0; i < putNumberUsed.count; i++) {
    int randomInt1 = arc4random() % [putNumberUsed count];
    int randomInt2 = arc4random() % [putNumberUsed count];
    [putNumberUsed exchangeObjectAtIndex:randomInt1 withObjectAtIndex:randomInt2];
}

我这可能对你有用。

于 2012-06-27T10:50:04.043 回答
5

这是一个洗牌解决方案,当 count > 1 时,所有位置都被迫改变。

添加 NSMutableArray+Shuffle.m 之类的类别:

@implementation NSMutableArray (Shuffle)
// Fisher-Yates shuffle variation with all positions forced to change
- (void)unstableShuffle
{
    for (NSInteger i = self.count - 1; i > 0; i--)
        // note: we use u_int32_t because `arc4random_uniform` doesn't support int64
        [self exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
}
@end

然后你可以像这样洗牌:

[putNumbersUsed unstableShuffle];

这个解决方案:

Swift 3.2 和 Swift 4 等价物是:

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

Swift 3.0 和 3.1 的等效版本是:

extension Array {
    mutating func unstableShuffle() {
        for i in stride(from: count - 1, to: 0, by: -1) {
            swap(&self[i], &self[Int(arc4random_uniform(UInt32(i)))])
        }
    }
}

注意:还可以使用常规洗牌算法(可能有相同位置的结果)

于 2015-07-15T03:09:40.377 回答
3

从 iOS 10.x++开始,Apple 给出了shuffle 数组的新概念,

您需要导入框架:

对象

#import <GameplayKit/GameplayKit.h>

NSArray *shuffledArray = [yourArray shuffledArray];

迅速

import GameplayKit

let shuffledArray = yourArray.shuffled()
于 2017-06-06T07:01:13.110 回答
2

您可以使用以下代码行随机播放对象,

[putNumbersUsed exchangeObjectAtIndex:3 withObjectAtIndex:0];

我认为这可能对你有用。

于 2012-06-27T10:28:15.653 回答
1

为索引生成一个随机数

int randomInt = arc4random() % [putNumberUsed count];
[putNumberUsed objectAtIndex:randomInt];
于 2012-06-27T10:22:59.233 回答
0

用这个:

for (int i = 0; i < [putNumberUsed count]; i++) {
    int random = arc4random() % [putNumberUsed count]; 
    [putNumbersUsed exchangeObjectAtIndex:random withObjectAtIndex:i]; 
}
于 2012-06-27T10:51:15.680 回答