سؤال

I have 10 UIButtons created in historyboard, OK?
I want to add random numbers that do not repeat these numbers, ie, numbers from 0 to 9 that interspersed whenever the View is loaded.

I tried to find on Google and here a way to use my existing buttons ( 10 UIButton ), and just apply them to random values​​. Most ways found ( arc4random() % 10 ), repeat the numbers.

All results found that creating buttons dynamically. Anyone been through this?

هل كانت مفيدة؟

المحلول

Create an array of the numbers. Then perform a set of random swapping of elements in the array. You now have your unique numbers in random order.

- (NSArray *)generateRandomNumbers:(NSUInteger)count {
    NSMutableArray *res = [NSMutableArray arrayWithCapacity:count];
    // Populate with the numbers 1 .. count (never use a tag of 0)
    for (NSUInteger i = 1; i <= count; i++) {
        [res addObject:@(i)];
    }

    // Shuffle the values - the greater the number of shuffles, the more randomized
    for (NSUInteger i = 0; i < count * 20; i++) {
        NSUInteger x = arc4random_uniform(count);
        NSUInteger y = arc4random_uniform(count);
        [res exchangeObjectAtIndex:x withObjectAtIndex:y];
    }

    return res;
}

// Apply the tags to the buttons. This assumes you have 10 separate ivars for the 10 buttons
NSArray *randomNumbers = [self generateRandomNumbers:10];
button1.tag = [randomNumbers[0] integerValue];
button2.tag = [randomNumbers[1] integerValue];
...
button10.tag = [randomNumbers[9] integerValue];

نصائح أخرى

@meth has the right idea. If you wanna make sure the numbers aren't repeating, try something like this: (note: top would the highest number to generate. Make sure this => amount or else this will loop forever and ever and ever ;)

- (NSArray*) makeNumbers: (NSInteger) amount withTopBound: (int) top
{ 
     NSMutableArray* temp = [[NSMutableArray alloc] initWithCapacity: amount];

     for (int i = 0; i < amount; i++)
     {
        // make random number
        NSNumber* randomNum; 

        // flag to check duplicates
        BOOL duplicate;

        // check if randomNum is already in your array
        do
        {
            duplicate = NO;
            randomNum = [NSNumber numberWithInt: arc4random() % top];

            for (NSNumber* currentNum in temp)
            {
                if ([randomNum isEqualToNumber: currentNum])
                {
                    // now we'll try to make a new number on the next pass
                    duplicate = YES;
                }
            }
        } while (duplicate)

        [temp addObject: randomNum];
    }

    return temp;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top