【问题标题】:Pick 4 random elements from an NSArray of count 6从计数为 6 的 NSArray 中选择 4 个随机元素
【发布时间】:2013-10-02 02:32:00
【问题描述】:

我是 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 数组中,但我想知道是否有更简单的方法做事?

谢谢

【问题讨论】:

  • 那么,这个作业什么时候交?
  • 虽然明显是功课,但我觉得这种问题还可以。发帖人已经证明他们对自己的工作有足够的了解,并要求提供补充信息以提高他们的知识

标签: objective-c nsarray


【解决方案1】:

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

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

【讨论】:

  • 您能提供更多信息吗?我的笔记说你不能向 NSArray 添加或删除一个对象,除非它是 NSMutableArray。那么如何从“allColors”中删除呢?哦——现在我明白了!您正在创建一个 mutableCopy!好的。很有创意。
  • 我也在下面发布了我的解决方案,但你的更好。
【解决方案2】:
 //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 上面的回复。

【讨论】:

  • 这是一种非常糟糕的选择不匹配随机数的方法。性能可能很糟糕
  • 您对如何检查唯一匹配号码有更好的建议吗?
【解决方案3】:

保留原始源列表:

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]];
}

【讨论】:

    猜你喜欢
    • 2016-03-26
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多