G
guptan
My problem is sometimes the getRandom(int low, int high) function
returns negative values.
Please review this code
import java.util.Random;
public class RNG
{
private Random random;
public RNG() {
if(random == null){
random = new Random(System.currentTimeMillis());
}
random.setSeed(System.currentTimeMillis());
}
public void setSeed(long l) {
random.setSeed(l);
}
public int getRandom(int max) {
return (max == 0) ? 0 : (Math.abs(random.nextInt() % max));
}
///get random in range int the closed range [low, mid]
public int getRandom(int low, int high) {
if(low > high) {
int t = low;
low = high;
high = t;
}else if(low == high) {
return low;
}
int range = (high - low) + 1;
return low + ((range * getRandom(100))/100);
}
}
returns negative values.
Please review this code
import java.util.Random;
public class RNG
{
private Random random;
public RNG() {
if(random == null){
random = new Random(System.currentTimeMillis());
}
random.setSeed(System.currentTimeMillis());
}
public void setSeed(long l) {
random.setSeed(l);
}
public int getRandom(int max) {
return (max == 0) ? 0 : (Math.abs(random.nextInt() % max));
}
///get random in range int the closed range [low, mid]
public int getRandom(int low, int high) {
if(low > high) {
int t = low;
low = high;
high = t;
}else if(low == high) {
return low;
}
int range = (high - low) + 1;
return low + ((range * getRandom(100))/100);
}
}