Assign character at an index to a random character

Viewed 24

I have this class called Organism:

import java.util.Random;

public class Organism {

    // Represents the organisms guess for the unknown string
    String value;
    // String the organism is trying to guess
    String goalString;
    int n;

    public Organism(String goalString) {
        this.goalString = goalString;
        this.value = goalString;
    }

    public Organism(String value, String goalString, int n) {
        this.goalString = goalString;
        this.value = value;
        this.n = n;
    }

    public int fitness(){
        // Represents the fitness of the organism
        int count = 0;

        for(int i = 0; i < goalString.length(); i++) {
            if(value.charAt(i) == goalString.charAt(i)) {
                count ++;
            }
        }
        return count;
    }

    public Organism[] mate(Organism other) {
        // Generate a random int
        Random rand = new Random();
        int crossOver = rand.nextInt(n);

        // Create 2 strings
        String child1 = "", child2 = "";
        for (int i = 0; i < crossOver; i++) {
            child1 = child1 + this.value.charAt(i);
            child2 = child2 + other.value.charAt(i);
        }

        // Create an array of 2 organisms
        Organism[] children = new Organism[2];
        children[0] = new Organism(goalString, child1, n);
        children[1] = new Organism(goalString, child2, n);

        return children;
    }

    public void mutate(double mutateProb) {
        for (int i = 0; i < value.length(); i++) {
            Random rand = new Random();
            int r = rand.nextInt(2);
            if (r > mutateProb) {
                System.out.println("Mutate probability out of range");
            } else {
                String s = "abcdefghijklmnopqrstuvwxyz  ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                char[] chars = s.toCharArray();
                int randIndex = rand.nextInt(chars.length);
                char randomChar = chars[randIndex];
               // Assign value.charAt(i) = randChar
            }
        }
    }

    @Override
    public String toString() {
        return "Value: " + value + "    " + "Goal: " + goalString + "    " + "Fitness: " + fitness();
    }


    public String getValue() {
        return value;
    }

    public String getGoalString() {
        return goalString;
    }

    public int getN() {
        return n;
    }

}

Under the mutate method I need to assign value.charAt(i) to the new random character that is generated from the chars array using the randomChar variable. I keep getting an error though and I am unsure why. What would be the best way to do this without getting an error?

0 Answers
Related