dimanche 16 juin 2019

Get a random number within a range with a bias

Hello i am trying to make a method to generate a random number within a range where it can take a Bias that will make the number more likely to be higher/lower depending on the bias.

To do this currently i was using this

 public int randIntWeightedLow(int max, int min, int rolls){

    int rValue = 100;

    for (int i = 0; i < rolls ; i++) {
        int rand = randInt(min, max);

        if (rand < rValue ){
            rValue = rand;
        }
    }

    return rValue;
}

This works okay by giving me a number in the range and the more rolls i add the likely the number will be low. However the problem i am running in to is that the there is a big difference between having 3 rolls and 4 rolls.

I am loking to have somthing like public void randomIntWithBias(int min, int max, float bias){ }

Where giving a negative bias would make the number be low more often and a positive bias make the number be higher more often but still keeping the number in the random of the min and max.

Currently to generate a random number i am using

 public int randInt(final int n1, final int n2) {
    if (n1 == n2) {
        return n1;
    }

    final int min = n1 > n2 ? n2 : n1;
    final int max = n1 > n2 ? n1 : n2;

    return rand.nextInt(max - min + 1) + min;
}

I am new to java and coding in general so any help would be greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire