Question

I'm having trouble (all sorts of different ones), with my mutation function for an Genetic algorithm. I manipulate strings as DNA, which come from Integer.toString(Float.floatToIntBits(value)). Everything cross-over nicely, and repopulates, so now its time for some nasty mutations. And now i have a problem, this is my mutation function:

public void muttate() {
    Random rand = new Random();
    int mutationPoint = rand.nextInt(valueString.length()-1);
    //int mutationPoint=valueString.length()-1;
    //System.out.println(mutationPoint);
    if(mutationPoint==0)
        valueString = rand.nextInt(10)
        + valueString.substring(0);
    else if (mutationPoint == 1)
        valueString = valueString.charAt(0)
                + Integer.toString(rand.nextInt(10))
                + valueString.substring(mutationPoint);
    else if (mutationPoint != valueString.length()-1)
        valueString = valueString.substring(0, mutationPoint-1)
                + Integer.toString(rand.nextInt(10))
                + valueString.substring(mutationPoint);
    else
        valueString = valueString.substring(0, mutationPoint - 1)
                + Integer.toString(rand.nextInt(10));
    changeStringtovalue();
    calculateFitnes();
}

and as i run it, i see it eats up my DNA (so length is first 9, then after some time is 8 and so long). And it comes from this mutation part, not cross-overs (tested). I think it's some kind of stupid mistake, but i just can't find a clue.

And also, is that kind of mutation even valid for this situation? Maybe I should manipulate bits, after applying masks, to get to certain part of that float.

Was it helpful?

Solution

Mutate is spelled without the double tt. Your code will never mutate the last position because of the way you call random.

The problem is substring(start, end) returns a string that does not include the end index character. So you're losing one character. The whole if block is unneeded as well. If you're trying to mutate, you could write a function like this:

public void mutate() {
    Random rand = new Random();
    int mutPos = rand.nextInt(valueString.length());
    valueString = valueString.substring(0, mutPos) 
        + rand.nextInt(10) + valueString.substring(mutPos+1);
}

Here's some tips:

Given string "ABC".

substring(1,2) returns "B", index 1 inclusive to index 2 exclusive.

substring(0, string.length()) return whole string.

substring(0) returns whole string.

substring(i, i) returns ""

Substring also returns "" if it starts (and ends) at index one past the last character (at string.length() index.

This allows you to easily handle corner cases without if sentences as demonstrated in the code I wrote above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top