Friday, March 30, 2007

I love to function

While working on my piece of piss Java assignment, i came up with a neat little random number generating function. It's a mirror of a function that is commonly used by Objective-C developers, and allows you to have random numbers but within a range. I've casted the result before i return to the calling routine, so you simply change or remove the cast to get the primitive of your choice, as it's all Floating point arithmetic.

Java



private int randomIntWithinRange(int pLow, int pHighest, boolean pDebug){
boolean acceptableValue = false;
double possibleValue;
double finalValue = - 0.1;
int attemptsTillSuccess = 0;

//If the value is not acceptable continue
while(!acceptableValue){
possibleValue = Math.random() * (pHighest * 10);

if(possibleValue >= pLow && possibleValue <= pHighest){
finalValue = possibleValue;
acceptableValue = true;
}
else{
attemptsTillSuccess++; //How many times
}

}

if(pDebug){
System.out.println("" + attemptsTillSuccess + " attempt(s) till success"); //debuging
}

return (int)finalValue;
}

It's even does a little debugging line, so you can see the number of attempts till it succeeds. Released under the GPL 2.0, For use in non-commercial products yada yada. When i can be asked i'll write a Javascript, and C version, and if i feel really nice a VB version.

Update: With me having banned myself from facebook for a while, i thought i would make myself more useful and covert the java to ECMA script, of Javascript for lesser clued up, wasn't hard just replaced primitive declarations with var ^_^.

Javascript



function randomIntWithinRange( pLowest, pHighest, pDebug ){
var acceptableValue = false;
var possibleValue;
var finalValue;
var attemptsTillSuccess;

while(!acceptableValue){
possibleValue = Math.random() * (pHighest * 10 );

if(possibleValue >= pLow && possibleValue <= pHighest){
finalValue = possibleValue;
acceptableValue = true;
}
else{
attemptsTillSuccess++; //How many times
}
}

if(pDebug){
Document.write(attemptsTillSuccess + " attempts till success"); //debuging
}

//Damn loosely typed language!!
return Math.round(finalValue);



PS. I didn't test the javascript version, so don't count on it to work straight off the bat.

No comments: