1

我是 Objective C 的新手。我正在编写游戏 Mastermind,其中计算机从 6 种颜色中选择 4 种随机颜色,用户尝试在 6 次尝试中猜测 4 种颜色。

我有一个 NSArray 来代表所有六种可能的颜色:

    NSArray * allColors = [[NSArray alloc] initWithObjects:@"r", @"g", @"b", @"y", @"p", @"o", nil];

    //Computer choose 4 random colors:

    NSArray * computersSelection = [[NSArray alloc] init];

我需要编写代码从数组中选择 4 种唯一的随机颜色。有没有聪明的方法来做到这一点?

我可以创建四个 int 变量并使用 while 循环生成四个随机数,然后根据四个随机整数值从 NSArray 中提取对象并将它们放入 computerSelection 数组中,但我想知道是否有更简单的做事方式?

谢谢

4

3 回答 3

4

由于初始数组是固定的,因此确保唯一值的一种相对简单的方法是删除对象而不是选择它们。在这种情况下,删除两个,你就有一个四个数组,保证唯一性。这是基本代码:

    NSArray *allColors = @[@"r", @"g", @"b", @"y", @"p", @"o"];
    NSMutableArray *fourColors = [allColors mutableCopy];
    [fourColors removeObjectAtIndex:arc4random_uniform((u_int32_t)(fourColors.count + 1))];
    [fourColors removeObjectAtIndex:arc4random_uniform((u_int32_t)(fourColors.count + 1))];
    NSLog(@"%@", fourColors);
于 2013-10-02T02:58:28.203 回答
1
 //0 r
    //1 g
    //2 b
    //3 y
    //4 p
    //5 o
    NSArray * allColors = [[NSArray alloc] initWithObjects:@"r", @"g", @"b", @"y", @"p", @"o", nil];

    //Computer choose 4 random colors:

    NSUInteger x1 =1;
    NSUInteger x2 =1;
    NSUInteger x3 =1;
    NSUInteger x4 =1;

    while(x1 == x2 || x1 == x3 || x1 == x4 || x2 == x3 || x2 == x4 || x3 == x4)
    {
        x1 = arc4random() % 6;
        x2 = arc4random() % 6;
        x3 = arc4random() % 6;
        x4 = arc4random() % 6;
    }
    NSArray * computersSelection = [[NSArray alloc] initWithObjects: [allColors objectAtIndex: x1], [allColors objectAtIndex: x2], [allColors objectAtIndex: x3], [allColors objectAtIndex: x4], nil];

    NSLog(@"%@, %@, %@, %@", [computersSelection objectAtIndex:0], [computersSelection objectAtIndex:1], [computersSelection objectAtIndex:2], [computersSelection objectAtIndex:3]);

所以这是我的尝试。但我仍然更喜欢@jshier 上面的回复。

于 2013-10-02T03:19:09.663 回答
0

保留原始源列表:

NSUInteger const kChoiceSize = 4;
NSArray * allColors = [[NSArray alloc] initWithObjects:@"r", @"g", @"b", @"y", @"p", @"o", nil];

NSMutableSet *choice = [[NSMutableSet alloc] init];
while ([choice count] < kChoiceSize) {
    int randomIndex = arc4random_uniform([allColors count]);
    [choice addObject:[allColors objectAtIndex:randomIndex]];
}
于 2013-10-02T03:25:24.003 回答