Search code examples
javafitness

Java Fitness Function Not Working


I have a fitness function as part of a lab and wish to apply it to a set of 'weights' (ArrayList weights). I have created the array and stored some values in it. I have created random binary strings (which have an 'x' at the end in order to generate random values) which I wish to also apply the fitness function to; however, the problem I am having is that the fitness function always returns a value of 0. Am I missing something here?

The fitness function is as follows:

public static double scalesFitness(ArrayList<Double> weights){  
    if (scasol.length() > weights.size()) return(-1);
    double lhs = 0.0,rhs = 0.0;

    double L = 0.0;
    double R = 0.0;

    for(int i = 0; i < scasol.length(); i++){
        if(scasol.charAt(i) == '0'){
        L = L += 0;
    }
    else if(scasol.charAt(i) == '1'){
        R = R += 1;
    }
    }//end for

    int n = scasol.length();

    return(L-R);

}

Random binary string method:

private static String RandomBinaryString(int n){
    String s = new String();

    for(int i = 0; i <= n; i++){
        int y = CS2004.UI(0,1);
            if(y == 0){
                System.out.print(s + '0');
            }
            else if(y == 1){
                System.out.print(s + '1');
            }
    }

    return(s);
}

Main method (in separate class):

public static void main(String args[]){

    for(int i = 0; i < 10; i++){
        ScalesSolution s = new ScalesSolution("10101x");
        s.println();
    }

    ArrayList<Double> weights = new ArrayList<Double>();

        weights.add(1.0);
        weights.add(2.0);
        weights.add(3.0);
        weights.add(4.0);
        weights.add(10.0);
        System.out.println();

    System.out.print("Fitness: ");
    System.out.print(ScalesSolution.scalesFitness(weights));
}

Once run, the random binary strings work perfectly well, yet the fitness function fails to change from 0. Here is a sample output:

1101100
1100111
0001111
1001010
1110000
0011111
1100111
1011001
0000110
1000000

Fitness: 0.0

If you wish to code for the whole class(es), then please let me know.

Thank you all so much for your time.

Mick.


Solution

  • Looks to me like you're always returning a blank String from RandomBinaryString() - you print out some digits but never actually append them. Use s = s+'0', or s += '0', or s.concat("0") ,or use a StringBuilder , etc...

    I'm assuming scasol is your binary string, so that's empty, then nothing in your for loop gets called once, so L and R both stay at 0.0, and you wind up returning 0.0.