[Objective-C] Random problems.

September 16, 2015

Intro

Random is a very interested problem, to help to create a random number, string, … easily. It makes convenience to create simple game just like #AiLaTrieuPhu, #FreakingMath or #YouStupid … So today, I’m very glad to share with you guys something I know about Random by using Objective-C.

Now, Let’s roll

How to generate a random number

Many ways to do this, I usually use:

  • arc4random() - which is returned u_int32_t value. Theoretically, it has twice the range of rand(3) or random(3).
  • The one I use the most, it is arc4random_uniform(), to get a random number with bound. Just like:
	// return random number between 0 and N-1
	NSUInteger r = arc4random_uniform(N);
	// return random number between 1 and N
	NSUInteger r = arc4random_uniform(N)+1;

or just use C:

	#include <stdlib.h>
	int r = rand() % N

if you want to use random():

	#import <stdlib.h>
	#import <time.h>

	// you need to seed it once
	srandom(time(NULL));
	random() % N;

How to generate from … to …

The snipet code I’ve been using:

-(int) generateRandomNumberWithlowerBound:(int)lowerBound
                               upperBound:(int)upperBound
{
    int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
    return rndValue;
}

How to generate double or float number

We use like:

	srand48(time(0));
	double r = drand48()

Just like srandom(), we need to seed before using, and it should be run only once.

More

With some techniques above, we can easily work with Random numbers. Moreover, we can use it for string, that is we can generate a random string, random char …

How to generate a random char

  • for Lower Case:
	NSString *letter = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'a'];
  • for Upper Case:
	NSString *letter = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'A'];

How to generate a random String

Base on thing above, we have:

	int stringLengh = 4;
    NSString *finalString = @"";
    
    for (int i = 0; i < stringLengh; i++) {
       NSString *newString = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'a'];
        finalString = [finalString stringByAppendingString:newString];
    }

We could use it for generating Upper Case as well. But in case we want to create a lower and upper case string, just do like this:

	int stringLengh = 4;
    NSString *finalString = @"";
    
    for (int i = 0; i < stringLengh; i++) {
    	// if upperCase = true, show char in uppercase
    	// if upperCase = false, show char in lower
        BOOL upperCase = (BOOL)arc4random_uniform(2);
        NSString *newString = [NSString stringWithFormat:@"%c", arc4random_uniform(26) + (upperCase ?'A':'a')];
        finalString = [finalString stringByAppendingString:newString];
    }

End

So these are some interesting paths while working with random problems. Hope you can find something fun.

Again, happy coding. And share your points.