Search code examples
javarandompercentageadjustable

Java: Gender Control


So in my simulator I am trying to more accurately control what the chance for a gender a creature will be when it is created. Originally I just had a straight 50% chance for each using RND, however I realise this will cause problems later. Therefore I was thinking of each time a creature is made and the gender being decided I could alter/adjust the % chance for each gender based on the current ratio, e.g. when the current population is 70% male and 30% female. So could make the next creature have a 70% chance of being female and do it like that. My issue is that I am struggling with a good way of implementing this, some information below:

    public void setGender2() {
        int fper = gcount.get(ctype+Gender.F); int mper = gcount.get(ctype+Gender.M);
        int tcc = fper + fper;
        int gmf = rNum(0,100); //Calls the random number method.
        if (fper == mper) { //When first used the total will be 0 so do this.
            gchance = 50;
            if (gmf <= gchance) g = Gender.F; //If the random number is less than the calculated gchance %.
            else g = Gender.M;
        }
        else {
            gchance = (int)(100-(((double)gcount.get(ctype+g)/(double)tcc)*100)); //Calculates the % for a gender.
            if (fper < mper) { //When there is less females...
                if (gmf <= gchance) g = Gender.F;
                else if (gmf > gchance) g = Gender.M;
            }
            else if (mper < fper) { //When there is less males...
                if (gmf <= gchance) g = Gender.M;
                else if (gmf > gchance) g = Gender.F;
            }
        }

        gcount.replace(ctype+g, gcount.get(ctype+g)+1); //update the count for this creature type + gender.
}

Gender information is stored in a HashMap called gcount. Each creature type & gender is a key, e.g. Fish (ctype) + Gender - and then a value stored with it, which is altered by the replace command at the bottom.

The thing is implementing it this way just seems very...untidy, so hoping others had some better suggestions...?

Thanks.


Solution

  • I would try something like this...

    int males = 2;  // <- your map value here
    int females = 1;  // <- your map value here
    
    int total = males + females;
    
    double chanceMale = .5;
    
    if (total > 0) {
    
        chanceMale = females / (double)total;
    
    } 
    

    And then simply compare your random number to chanceMale * 100, to find out if it's a male (otherwise female).