Fools ignore complexity; pragmatists suffer it; experts avoid it; CREATIVES remove it.

Thursday, September 20, 2007

Float random in 15 minutes

I was reading Gamasutra website when I saw an interesting job offer, please check out, http://jobs.gamasutra.com/jobseekerx/viewjobrss.asp?cjid=12163&accountno=219
I couldn't avoid write that function they are describing in the first part of test.

* The function rand_FloatRange(float a, float b) returns a random float number, 'x', such that a <= x <= b.

I’ve decided to invest 15 minutes from my spare time, so after 5 minutes trying the conventional approach I just decided change strategy in order to make that function work in the last 10 minutes; Pressing creative button all became clear: we need to return a number that needs match AB range, the difference between A and B can be considered a distance as well, a percent, that was my approach:

float rand_FloatRange(float a, float b)
return ((b-a)*((float)rand()/RAND_MAX))+a;

All I did was transform conventional rand() in percent, now that I’ve a percent I can apply that to range between A and B, it doesn't matter if they are negative or positive values, easy, huh?

that’s all!!! nothing bad for 15 minutes

Keep creative!

No comments: