Question

I have a very basic random number function which generates a random number from a range;

ie:

// The random is seeded earlier on in the applicationDidFinishLaunching() function
-(NSUInteger)makeRandomNumber:(NSUInteger)minNumber to:(NSUInteger)maxNumber
{
 //NSUInteger i = (NSUInteger)( (random() / (double)RAND_MAX) * y);

 NSUInteger i = (arc4random() % (maxNumber - minNumber)) + minNumber; 
 return i;
}

I want to add an optional modulus operation to this function, so that you only return numbers that are modulus of something.

I'm wanting to do this to generate Wages for random people, I find that wages that round with a 5 or 0 much more readable.

I'm not sure how to make an optional parameter or force the randomisation to continue looping until it has found the optional modulus value.

Another issue is that sometimes the loop can continue forever if there is no modulus to find.

ie;

Randomise between 0 and 100 and return a value that is modulus of 5.

EDIT: This should work with any range, regardless of what min or max are. The above numbers are just examples.

Was it helpful?

Solution

ITYM multiple of 5. For your example you would just generate a random value between 0 and 20 then multiply this by 5.

OTHER TIPS

I think a loop will work well enough:

 NSUInteger i = 0;
 do {
   NSUInteger i = (arc4random() % (maxNumber - minNumber)) + minNumber; 
 } while(i % 5 != 0);

Integer division will make sure your number is a multiple of roundNumber only as it truncates the decimal in the divide, and then restores the original rounded number in the multiply.

// The random is seeded earlier on in the applicationDidFinishLaunching() function
-(NSUInteger)makeRandomNumber:(NSUInteger)minNumber to:(NSUInteger)maxNumber round:(NSUInteger) roundNumber
{   
 NSUInteger i = (arc4random() % (maxNumber - minNumber)) + minNumber; 
 return (i / roundNumber) * roundNumber;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top