从列表中选择不带重复的随机字符填充数组 [英] Fill an array with random characters chosen from a list without duplicates

查看:130
本文介绍了从列表中选择不带重复的随机字符填充数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用6个不同字符中的4个来填充数组,其中数组中的每个字符都不同。放入数组的字符基于switch语句。然后我想回到数组,以确保我刚刚放置的字符不是已经在数组中,如果它是我必须放入一个不同的字符。我如何做到这一点?我不想重新填充整个数组,只是这一个点。

I am trying to fill an array with 4 of 6 different characters where each character in the array is different. The character that is placed into the array is based on a switch statement. Then I want to go back through the array to make sure the character I just placed is not already in the array and if it is I have to put in a different character. How do I do this? I don't want to refill the whole array, just this one spot.

这是我到目前为止的代码,评论包括:

This is the code I have so far, comments included:

-(void) fillarray{

for (int i=0; i<4; i++)
{
    int randomNum = arc4random() % 6; // generates a random number

          switch (randomNum) // based on the number generated, it choses what color will be placed into the slot
    {
        case 1:
            colorarray[i] ='r';
            break;

        case 2:
            colorarray[i] ='o';
            break;

        case 3:
            colorarray[i] ='y';
            break;

        case 4:
            colorarray[i] ='g';
            break;
        case 5:
            colorarray[i] = 'b';

        case 6:
            colorarray[i] = 'p';

        default:
            break;
    }

    for (int j=0; j<4; j++) // runs through the array to ensure that the recently placed color does not match previous placed colors
    {
        while (j /= i)

            if (colorarray[i]==colorarray[j]) // if the color is already in the array
                                            //try again to place another color in this location

    }


推荐答案

NSArray * array = @[ @"r", @"o", @"y", @"g", @"b", @"p" ] ;
array = [ [ array shuffledArray ] subarrayWithRange:(NSRange){ .length = 4 } ] ;

其中 -shuffledArray 被添加到NSArray

Where -shuffledArray is added to NSArray by:

@implementation NSArray ( Shuffling )

-(NSArray*)shuffledArray
{
    NSMutableArray * result = [ NSMutableArray arrayWithCapacity:self.count ] ;
    [ result addObject:self[0] ] ;
    for( NSUInteger index=1, count = self.count; index < count; ++index )
    {
        int j = arc4random_uniform( (unsigned int)index ) ;
        [ result addObject:result[j] ] ;
        [ result replaceObjectAtIndex:j withObject:self[ index ] ] ;
    }

    return result ;
}

@end

这篇关于从列表中选择不带重复的随机字符填充数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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