随机播放NSMutableArray

时间:2012-06-27 10:20:44

标签: objective-c ios xcode

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

 [putNumberUsed objectAtIndex:0] 
除了“blah1”,它会给我任何东西。我该怎么做呢?以下是我目前使用的代码,提前感谢

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

6 个答案:

答案 0 :(得分:9)

我想,你可以为此写一个循环。请检查以下代码,

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

我认为这对你有用。

答案 1 :(得分:7)

来自iOS 10.x ++新concept of shuffle array由Apple提供,

您需要导入框架:

<强> ObjeC

#import <GameplayKit/GameplayKit.h>

NSArray *shuffledArray = [yourArray shuffledArray];

<强>夫特

import GameplayKit

let shuffledArray = yourArray.shuffled()

答案 2 :(得分:4)

这是一个改组解决方案,当计数时,所有位置都被迫改变&gt; 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)))])
        }
    }
}

注意:An algorithm for regular shuffling (where a result with same positions being possible) is also available

答案 3 :(得分:2)

您可以使用以下代码行

来对对象进行随机播放
[putNumbersUsed exchangeObjectAtIndex:3 withObjectAtIndex:0];

我认为这对你有用。

答案 4 :(得分:1)

为索引生成随机数

int randomInt = arc4random() % [putNumberUsed count];
[putNumberUsed objectAtIndex:randomInt];

答案 5 :(得分:0)

使用此:

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