【问题标题】:Shuffle NSArray随机播放 NSArray
【发布时间】:2015-06-10 05:26:40
【问题描述】:

我得到了一个 NSMutableArray,其中包含从 1 到最大 20 不等的少量对象。

当用户点击一个按钮时,我想选择一个随机对象并显示它。我试过改组数组:

srandom(time(NULL));
for (NSInteger x = 0; x < [array count]; x++)     {
    NSInteger randInt = (random() % ([array count] - x)) + x;
    [array exchangeObjectAtIndex:x withObjectAtIndex:randInt];

}

然后使用 arc4random() 选择一个随机索引,但我得到了很多重复。 我不想删除ObjectAtIndex,因为这只会将我的数组减少到零然后崩溃。 有没有办法用相同的对象重新填充数组,一旦达到零并重新开始?

谢谢

【问题讨论】:

    标签: ios8 nsarray


    【解决方案1】:

    如果你只需要选择一个随机对象,你可以使用以下。这将比实际改组数组更有效。

    uint32_t rnd = arc4random_uniform([array count]);
    
    MyObject *randomObject = [array objectAtIndex:rnd];
    

    Adam 记入this answer

    【讨论】:

    • 谢谢。这就是我正在做的事情。然而,因为它是少数条目,我得到重复。我只想要数组中的唯一数字,直到它达到最大array.count。然后它可以重复自己。
    【解决方案2】:

    我通过执行以下操作设法“解决”了我的问题: 它可能很乱,但我想对此提出一些意见。

    NSUInteger randomIndex = arc4random()% [_someArray count];
    
        if (array.count == 0) { //check if array is empty and add the randomIndex
            [array addObject:@(randomIndex)];
            randomTitle = [[_someArray objectAtIndex:randomIndex] myText];
    
            // NSLog(@"array is empty");
            // NSLog(@"my array content %@", array);
        }
    
        else if (array.count > 0 && array.count < _someArray.count) {//check if array has already an object and check if this is unique and add it to the array. if not run the loop again.
    
              NSLog(@"array is betwen 0 and _someArray.count");
    
            if([array indexOfObject:@(randomIndex)] == NSNotFound) {
                [array addObject:@(randomIndex)];
           randomTitle = [[_someArray objectAtIndex:randomIndex] myText];
    
              //  NSLog(@"unique number in array");
            }
    
            else {
    
                [self loopBackTheAction];
    
                // NSLog(@"number is alreday in array");
            }
        }
    
       else if (array.count == _someArray.count) {//check if the array is full and empty it. run the loop again.
    
           [array removeAllObjects];
           [self loopBackTheAction];
    
           //  NSLog(@"array is full running again the loop");
        }
    

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-02
      • 1970-01-01
      • 2016-12-29
      相关资源
      最近更新 更多