Bronze Challenge: My approach (complete randomization)


I love randomization :wink:

A block for getting random numbers within a range from the previous number, in 1/100 steps:

float (^randomChange)(int,int,float) = ^(int plusRange, int minusRange, float currentValue) { int cv = currentValue*100; plusRange += minusRange; int value = ((arc4random()%plusRange)-minusRange+cv)%101; if (value<0) { return (float)(101+value)/100; } return (float)value/100; };

A method to change the given color by a random value, using the block above:

- (UIColor*)changeColor:(UIColor *)currentColor
	//those numbers represent "plus range" and "minus range". They can be altered freely.
	int i = 10;
	int z = 10;
	//initialize the floats for the "current color" method
	float red = 0;
	float green = 0;
	float blue = 0;
	float alpha = 0;
	//split the colors
	[currentColor getRed:&red green:&green blue:&blue alpha:&alpha];
	//change the values
	red = randomChange(i,z,red);
	green = randomChange(i,z,green);
	blue = randomChange(i,z,blue);
	//put the color together again and return
	return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];

Of course, you have to set the currentColor to the circle color before the iteration in the “drawRect” method, then set the currentColor with the method above and itself as argument, in order to have a new color in the next iteration.


//set Color and thickness
CGContextSetLineWidth(ctx, 10);
UIColor *currentColor = [self circleColor];
[currentColor setStroke];

//draw a number of circles
for (float currentRadius = 0; currentRadius <maxRadius; currentRadius+=20) {
	CGContextAddArc(ctx, center.x, center.y, currentRadius, 0.0, M_PI*2.0, YES);
	[b]currentColor = [self changeColor:currentColor];[/b]
	[b][currentColor setStroke];[/b]


The advantage is, that if you don´t want too “assorted” colors, you can limit the range and have a nice kind of gradient. You could even use the block directly for only one color, that it is more determined which color you will get.
UIColor blackColor, UIColor whiteColor and all shades in between will not work with this code, because it cannot be properly split into RGBA colors (some problem with the color space, i guess.)


Use the arc4random_uniform function instead.
If this function is new to you, do man arc4random_uniform from the command line to see the manual page for it.


Thanks for the hint. I used rand() because it was used in RandomPossessions (an earlier chapter), and I did not know any other randomization so far. Also, I changed my code, because there was a mistake in the previous version where the block only returned the change and not the previous number PLUS the change, because of an integer conversion at the beginning of the block, when i passed the color value.