Bronze & Silver Challenges approaches


#1

Hi!

I’m posting my solutions before heading to gold challenge, hoping to hear your opinions to improve.

In this first one I didn’t get so well how to generate random numbers below 1, so if you could explain it to me I’ll really appreciate that.

[size=200]Bronze Challenge[/size]

[code]//Create random numbers between 0 and 1 for RGB
double redColor = ((double)rand()/(double)RAND_MAX);
double greenColor = ((double)rand()/(double)RAND_MAX);
double blueColor = ((double)rand()/(double)RAND_MAX);

    //Generate a new color based on previous values
    [self setCircleColor:[UIColor colorWithRed:redColor green:greenColor blue:blueColor alpha:1]];
    
    //Apply the color just created to the stroke
    [[self circleColor] setStroke];[/code]

[size=200]Silver Challenge[/size]

[code]/********************************************************************************************************/
//Create a green crosshair in the middle

//Save the current context parameters (for shadow)
CGContextSaveGState(ctx);

//Disable shadow
CGContextSetShadowWithColor(ctx, offset, 0.0, NULL);

//Set stroke color for crosshair
[[UIColor greenColor] setStroke];

//Move current context to the center at top of the text
CGContextMoveToPoint(ctx, center.x, textRect.origin.y);
CGContextAddLineToPoint(ctx, center.x, textRect.origin.y - 60);

//Draw the vertical line
CGContextStrokePath(ctx);

//Set the coordinates to draw over the x axis
CGContextMoveToPoint(ctx, center.x - 30, textRect.origin.y - 30);
CGContextAddLineToPoint(ctx, center.x + 30, textRect.origin.y -  30);

//Draw the horizontal line
CGContextStrokePath(ctx);

//Restore the previous context for shadow parameter
CGContextRestoreGState(ctx);[/code]

Thanks in advance.


#2

To generate a random number >= 0, use the function arc4random:

u_int32_t arc4random (void);

To generate a random number >= 0 but less than some upper bound, use the function arc4random_uniform:

u_int32_t arc4random_uniform (u_int32_t upper_bound);

They give you perfectly good random numbers and are much easier to use.


#3

Thank you ibex, I guess this are more “real” random numbers, better than rand() and random()?