Reading random values from an array

前端 未结 5 1273
长情又很酷
长情又很酷 2021-01-18 11:39

I have an array with a 14 strings. I want to display each of these 14 strings to the user without duplicates. The closest I got was creating an array of integers and shuffli

5条回答
  •  难免孤独
    2021-01-18 12:10

    By "without duplicates" I assume you mean that you want to use each string in the array once before you use the same string again, not that you want to filter the array so it doesn't contain duplicate strings.

    Here's a function that uses a Fisher-Yates shuffle:

    /** @brief Takes an array and produces a shuffled array.
     *
     *  The new array will contain retained references to 
     *  the objects in the original array
     *
     *  @param original The array containing the objects to shuffle.
     *  @return A new, autoreleased array with all of the objects of 
     *          the original array but in a random order.
     */
    NSArray *shuffledArrayFromArray(NSArray *original) {
        NSMutableArray *shuffled = [NSMutableArray array];
        NSUInteger count = [original count];
        if (count > 0) {
            [shuffled addObject:[original objectAtIndex:0]];
    
            NSUInteger j;
            for (NSUInteger i = 1; i < count; ++i) {
                j = arc4random() % i; // simple but may have a modulo bias
                [shuffled addObject:[shuffled objectAtIndex:j]];
                [shuffled replaceObjectAtIndex:j 
                                    withObject:[original objectAtIndex:i]];
            }
        }
    
        return shuffled; // still autoreleased
    }
    

    If you want to keep the relationship between the riddles, hints, and questions then I'd recommend using a NSDictionary to store each set of related strings rather than storing them in separate arrays.

提交回复
热议问题