I have a java class that takes an array of numbers and an array of corresponding probabilities and acts as a random number generator that returns one of the numbers from the array according to the corresponding probabilities defined in the other other. How do I write a minimal but effective set of unit tests?
class RandomGen{
private int[] randomNums;
private float[] probabilities;
private float[] total_prob;
RandomGen(int[] randomNums, float[] probabilites) throws Exception{
if (this.set_arrays(randomNums, probabilites));
else {
throw new Exception("Invalid array format");
}
}
private boolean set_arrays(int[] randomNums, float[] probabilities){
if (check_arrays(randomNums, probabilities)) {
this.randomNums = randomNums;
this.probabilities = probabilities;
this.total_prob = new float[this.probabilities.length];
total_prob[0] = probabilities[0];
for (int i = 1; i < probabilities.length; i++){
total_prob[i] = total_prob[i-1] + probabilities[i];
}
return true;
}
return false;
}
public int[] return_randomNums(){
return this.randomNums;
}
public float[] return_probabilites(){
return this.probabilities;
}
private boolean check_arrays(int[] randomNums, float[] probabilities){
float total_prob = 0;
for (int i = 0; i < probabilities.length; i++){
if (probabilities[i] < 0) return false;
total_prob += probabilities[i];
}
if (randomNums.length != probabilities.length || total_prob != 1) return false;
return true;
}
public int nextNum(){
float random = (float) Math.random();
if (random <= total_prob[0]){
return randomNums[0];
}
for (int i=1; i < total_prob.length; i++){
if (total_prob[i-1] < random && random <= total_prob[i]) return randomNums[i];
}
return 0;
}
}
Aucun commentaire:
Enregistrer un commentaire