如何在不重复的情况下混洗 NSMutableArray [英] How to shuffle NSMutableArray without repetition

查看:57
本文介绍了如何在不重复的情况下混洗 NSMutableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
打乱 NSMutableArray 的最佳方法是什么?

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

Here in my code I want to shuffle the elements in the array and try to print it out, but it's not shuffling properly, I tried what is shown here.Its working but,it values are repating.

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);

            }
        }

    }

}

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

After shuffling the array values are repeating,pls help me to solve this issue

推荐答案

就做 NSMutableArray 的类

Just make the category of 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];
}

}

这篇关于如何在不重复的情况下混洗 NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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