【问题标题】:How to shuffle NSMutableArray without repetition [duplicate]如何在不重复的情况下随机播放 NSMutableArray [重复]
【发布时间】:2012-10-23 18:33:00
【问题描述】:

可能重复:
What’s the Best Way to Shuffle an NSMutableArray?

在我的代码中,我想对数组中的元素进行洗牌并尝试将其打印出来,但它没有正确洗牌,我尝试了here 显示的内容。它可以工作,但是它的值正在重复。

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIButton class]])
    { 
        button= (UIButton *)view;
        if (button.tag >=1 && button.tag <=20)
        {
            for (NSUInteger i = 0; i < count; ++i)
            {
                [texts rotate];
                // Select a random element between i and end of array to swap with.
                int nElements = count - i;
                int n = (arc4random() % nElements) + i;
                [texts exchangeObjectAtIndex:i withObjectAtIndex:n];
                //int myTag= j+1;
                //button = [self.view viewWithTag:myTag];
                name=[NSString stringWithFormat:@"%@",[texts objectAtIndex:n]];
                [button setTitle:name forState:UIControlStateNormal];
                NSLog(@"current  name :%@",name);

            }
        }

    }

}

洗牌后数组值重复,请帮我解决这个问题

【问题讨论】:

标签: iphone ios nsmutablearray


【解决方案1】:

只做NSMutableArray的类别

@implementation NSMutableArray (ArrayUtils)
-(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];
}

}

【讨论】:

  • NSMutableArary *arr = [NSMutableArray alloc]init]; [arr 随机播放];很容易
【解决方案2】:

试试这个int n = (arc4random() % count);
而不是
int n = (arc4random() % nElements) + i;

确保您将当前元素与 texts 中的任何元素交换,而不是始终在其后的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-10
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 2012-12-16
    • 1970-01-01
    相关资源
    最近更新 更多