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:
Post a Comment