I currently am making an app. My app involves having 3 different buttons that have randomized values from 1-3, however each value needs to be used up. So the way I set up my code is I have a method that randomizes a number and excludes certain numbers. This works perfectly with constants, however with these the values sometimes overlap and equal each other. Why is this happening?
private void randomizeKeys(){
key1 = (int)(Math.random()*3+1);
key2 = getRandomWithExclusion(new Random(),1,3,key1);
int[] arr1 = {key2,key1};
key3 = getRandomWithExclusion(new Random(),1,3,arr1);
}
private int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) {
int random = start + rnd.nextInt(end - start + 1 - exclude.length);
for (int ex : exclude) {
if (random < ex) {
break;
}
random++;
}
return random;
}
output example: key1 = 1, key2 = 2, key3 = 1 however key3 should equal 3
Aucun commentaire:
Enregistrer un commentaire