如何从NSArray获得独特的选择?

时间:2016-01-25 02:20:36

标签: ios objective-c

我已经编写了一个代码来从NSArray中选择一种随机颜色,但是如何才能使它不会连续两次选择相同的颜色呢?任何帮助将不胜感激。

+ (NSArray *)colors {

static NSArray *colors = nil;

static dispatch_once_t once;
dispatch_once(&once, ^{ colors = @[
//green
[UIColor colorWithRed:88.0/255.0 green:195.0/255.0 blue:98.0/255.0 alpha:1],
//yellow
[UIColor colorWithRed:246.0/255.0 green:194.0/255.0 blue:48.0/255.0 alpha:1],
//orange
[UIColor colorWithRed:236.0/255.0 green:135.0/255.0 blue:40.0/255.0 alpha:1],
//red
[UIColor colorWithRed:226.0/255.0 green:51.0/255.0 blue:40.0/255.0 alpha:1],
//blue
[UIColor colorWithRed:59.0/255.0 green:156.0/255.0 blue:218.0/255.0 alpha:1],
//violet
[UIColor colorWithRed:138.0/255.0 green:70.0/255.0 blue:165.0/255.0 alpha:1],
];
});

return colours; 
}

_selectedColor = [colors objectAtIndex: arc4random() % [colors count]];

2 个答案:

答案 0 :(得分:1)

随机抽取颜色数组,然后按顺序返回其元素。当你到达终点时,重新洗牌并重新开始。只要确保你不允许最后一个元素成为第一个避免连续两次返回相同元素的元素。这也可以保证每种颜色使用相同的次数。

@implementation UIColor (random)

static UIColor *rgb(CGFloat red, CGFloat green, CGFloat blue) {
    return [UIColor colorWithRed:red/255 green:green/255 blue:blue/255 alpha:1];
}

void shuffle(NSMutableArray *array) {
    // Based on http://stackoverflow.com/a/56656/77567
    NSUInteger count = array.count;
    if (count < 2) return;
    // Don't allow last element to become first, so you don't get the same color twice in a row.
    [array exchangeObjectAtIndex:0 withObjectAtIndex:arc4random_uniform(count - 1)];
    for (NSUInteger i = 1; i < count - 1; ++i) {
        NSInteger remainingCount = count - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
        [array exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }
}

+ (instancetype)randomColor {

    static dispatch_once_t once;
    static NSMutableArray *colors;
    static int nextColorIndex;
    static dispatch_queue_t queue; // serializes access to colors and nextColorIndex
    dispatch_once(&once, ^{
        colors = @[
            rgb(88, 195, 98), // green
            rgb(246, 194, 48), // yellow
            rgb(236, 135, 40), // orange
            rgb(226, 51, 40), // red
            rgb(59, 156, 218), // blue
            rgb(138, 70, 165), // violet
        ].mutableCopy;
        shuffle(colors);
        queue = dispatch_queue_create("UIColor+random.randomColor", 0);
    });

    __block UIColor *color;
    dispatch_sync(queue, ^{
        color = colors[nextColorIndex++];
        if (nextColorIndex == colors.count) {
            nextColorIndex = 0;
            shuffle(colors);
        }
    });
    return color;
}

@end

答案 1 :(得分:-1)

NSArray *colors = [NSArray new]; // ... //your code here
UIColor *selectedColor;

UIColor *randomColor; // your result

//choose random color but don't repeat the last one
randomColor = selectedColor;
while (randomColor == selectedColor) {
    randomColor = [colors objectAtIndex: arc4random() % [colors count]];
}